首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 泛型方法中實例化 T 類型的正確寫法

     編輯:程式設計綜合問答

錯誤代碼

void GetEntity() {
    if (this.Value == null) this.Value = new T(); // 編譯錯誤:T 必須有 new()
    return new T();
}

修正

T GetEntity() where T : class, new() {
    if (this.Value == null) this.Value = new T();
    return this.Value; // 返回已創建實例
}

約束解析

  • class:限定引用類型 (排除 struct)。
  • new():要求公共無參構造函數。
  • 若 T 為 struct,用 where T : struct + new() (C# 7.0+ 支持 default(T) 無需 new)。

用法

var entity = GetEntity(); // MyEntity 必須有 public MyEntity()
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved