Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

C# Generics won't allow Delegate Type Constraints

Is it possible to define a class in C# such that

class GenericCollection<T> : SomeBaseCollection<T> where T : Delegate

I couldn't for the life of me accomplish this last night in .NET 3.5. I tried using

delegate, Delegate, Action<T> and Func<T, T>

It seems to me that this should be allowable in some way. I'm trying to implement my own EventQueue.

I ended up just doing this [primitive approximation mind you].

internal delegate void DWork();

class EventQueue {
    private Queue<DWork> eventq;
}

But then I lose the ability to reuse the same definition for different types of functions.

Thoughts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A number of classes are unavailable as generic contraints - Enum being another.

For delegates, the closest you can get is ": class", perhaps using reflection to check (for example, in the static constructor) that the T is a delegate:

static GenericCollection()
{
    if (!typeof(T).IsSubclassOf(typeof(Delegate)))
    {
        throw new InvalidOperationException(typeof(T).Name + " is not a delegate type");
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...