我可以在同一个构造函数中使用泛型类和结构吗?

Gra*_*zer 0 c# generics

我对ServiceResponse对象的渴望是我想要回馈他们要求的"东西".这可能是一个Foo列表,只是一个Foo或几乎任何东西,只要它是一个带无参数构造函数的类.但是,有时候我想返回一个字节数组(byte [])并且不允许这样做,因为它是一个结构体,显然没有无参数构造函数.

public class ServiceResponse<T> : ServiceResponse where T : new() {

    [DataMember]
    public T Result { get; set; }

    public ServiceResponse() {
        this.WasSuccessful = false;
        this.Result = new T();
        this.Exceptions = new List<CountyException>(); ;
    }

    public ServiceResponse(bool wasSuccessful, List<CountyException> exceptions, T result) {
        this.Result = result;
        this.WasSuccessful = wasSuccessful;
        this.Exceptions = exceptions;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我将声明行调整为以下内容:

public class ServiceResponse<T> : ServiceResponse where T : new(), struct {
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

byte []必须是具有公共无参数构造函数的非抽象类型,以便在泛型类型方法ServiceResponse中将其用作参数T.

所以问题是,我可以使用一个类,它是一个泛型或结构的T吗?即使我必须看到它的类型,我认为它会很好.

Dan*_*rth 7

问题不在于struct.实际上,byte[]是一个引用类型(提示:数组).问题是,byte[]没有公共无参数构造函数,就像错误消息告诉你的那样


Jon*_*eet 6

摆脱new()约束.就C#而言,所有结构都有一个无参数构造函数,所以你仍然new T()只能使用约束where T : struct.

但是请注意,这byte[]不是一个值类型,因此它并不能满足该约束.

你有什么理由不想让它不受约束而不打扰Result构造函数中的设置吗?(或者default(T)如果你真的想要设置它.)