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

前端 未结 3 1060
孤独总比滥情好
孤独总比滥情好 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:45

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

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

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

提交回复
热议问题