C# Generics: Constraining T where T : Object doesn't compile; Error: Constraint cannot be special class 'object'

前端 未结 3 1062
孤独总比滥情好
孤独总比滥情好 2021-01-03 21:44

When I constrain T with : Object like this:

public interface IDoWork where T : Object
{
    T DoWork();
}

I get the error:

相关标签:
3条回答
  • 2021-01-03 22:31

    There is no difference between the two constraints, except for that one is disallowed for being useless to explicitly state.

    The C# 4.0 language specification (10.1.5 Type parameter constraints) says two things about this:

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

    ...

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

    In your comment, you said that you were trying to make T be of type Void. Void is a special type that indicates that there is no return type and cannot be used in place of T, which requires an appropriate concrete type. You will have to create a void version of your method and a T version if you want both.

    0 讨论(0)
  • 2021-01-03 22:33

    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.

    According to MSDN

    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)
  • 2021-01-03 22:45

    If you want to constrain a generic type to be a reference type, use : class.

    public interface IDoWork<T> where T : class
    {
        T DoWork();
    }
    

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

    0 讨论(0)
提交回复
热议问题