What exactly is a “Special Class”?

后端 未结 7 1917
鱼传尺愫
鱼传尺愫 2020-12-23 13:21

After failing to get something like the following to compile:

public class Gen where T : System.Array
{
}

with the error

相关标签:
7条回答
  • 2020-12-23 13:48

    As per C# 4.0 Language Specification (Coded : [10.1.5] Type parameter constraints) tells two things:

    1] The type must not be object. Because all types derive from object, such a constraint would have no effect if it were permitted.

    2] If T has no primary constraints or type parameter constraints, its effective base class is object.

    When you define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class. If client code tries to instantiate your class by using a type that is not allowed by a constraint, the result is a compile-time error. These restrictions are called constraints. Constraints are specified by using the where contextual keyword. If you want to constrain a generic type to be a reference type, use : class.

    public class Gen<T> where T : class
    {
    }
    

    This will prohibit the generic type from being a value type, such as int or a struct etc.

    Also, Constraint cannot be special class 'identifier' The following types may not be used as constraints:

    • System.Object
    • System.Array
    • System.Delegate
    • System.Enum
    • System.ValueType.
    0 讨论(0)
提交回复
热议问题