C# Generics won't allow Delegate Type Constraints

前端 未结 8 1280
别跟我提以往
别跟我提以往 2020-11-28 08:01

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

class GenericCollection : SomeBaseCollection where T : Delegate

I couldn

8条回答
  •  我在风中等你
    2020-11-28 08:19

    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");
        }
    }
    

提交回复
热议问题