zoukankan      html  css  js  c++  java
  • 泛型约束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;
            }
  • 相关阅读:
    高仿中国银行ATM系统
    第二次冲刺2
    第二轮冲刺1
    本日进度7
    本日进度6
    本日进度5
    本日进度4
    本日进度3
    本日进度2
    本日进度
  • 原文地址:https://www.cnblogs.com/chenh/p/10693018.html
Copyright © 2011-2022 走看看