开发者

Can we restrict the type be a delegate [duplicate]

开发者 https://www.devze.com 2023-01-24 11:42 出处:网络
This question already has answers here开发者_如何学编程: C# Generics won't allow Delegate Type Constraints
This question already has answers here开发者_如何学编程: C# Generics won't allow Delegate Type Constraints (8 answers) Closed 9 years ago.

We can restrict the type be the class or struct. Can we strict the type be a delegate?


A Delegate is a class, and you would normally be able to specify a non-sealed class as a constraint. However, the language specification specifically excludes System.Delegate as a valid constraint in section 10.1.5.

A class-type constraint must satisfy the following rules:

  • The type must be a class type.
  • The type must not be sealed.
  • The type must not be one of the following types: System.Array, System.Delegate, System.Enum, or System.ValueType.
  • The type must not be object. Because all types derive from object, such a constraint would have no effect if it were permitted.
  • At most one constraint for a given type parameter can be a class type.


As has already been pointed out, the C# specification does not allow a Delegate generic constraint. Nor are Delegate subclasses accepted by the compiler as a generic constraint. The best you can do is test and throw an exception. I will show this with a method, but if this is a generic class, the constructor would be a great place to do the check.

public void Foo<T>(T x)
{
    if (x == null)
        throw new ArgumentNullException("x");

    Delegate d = x as Delegate;
    if (d == null)
        throw new ArgumentException("Argument must be of Delegate type.", "x");

    // Use d here.
}
0

精彩评论

暂无评论...
验证码 换一张
取 消