C# Generics won't allow Delegate Type Constraints

前端 未结 8 1278
别跟我提以往
别跟我提以往 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:10

    Edit: Some proposed work-arounds are proposed in these articles:

    http://jacobcarpenters.blogspot.com/2006/06/c-30-and-delegate-conversion.html

    http://jacobcarpenters.blogspot.com/2006_11_01_archive.html


    From the C# 2.0 specification we can read (20.7, Constraints):

    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.

    And sure enough VS2008 spits out an error:

    error CS0702: Constraint cannot be special class 'System.Delegate'
    

    For info and investigation on this issue read here.

提交回复
热议问题