泛型约束new()的使用

  下面泛型约束代码,where字句后面有new()约束,T类型必须有公有的无参的构造函数。

private T InternalCreate<T>()
        where T : IObjectWithGuid, new()
        {
            T result = new T();  //不同于非泛型中的new
            result.Guid = Guid.NewGuid().ToString();
            return result;
        }

使用new关键字的作用只是让编译器在泛型实例化之处,检查所绑定的泛型参数T是否具有公共无参构造函数(public 无参构造函数),例如:InternalCreate<SomeType>(); //此处编译器会检查SomeType是否具有无参构造函数。若没有则会有compile error。

上面的代码等同于下面代码:

private T InternalCreate<T>()
        where T : IObjectWithGuid, new()
        {
            T result = System.Activator.CreateInstance<T>(); 
            result.Guid = Guid.NewGuid().ToString();
            return result;
        }
原文地址:https://www.cnblogs.com/chenh/p/10693018.html