![](/img/trans.png)
[英]How do I correctly constrain to related class type when using a generic method?
[英]How do you constrain a generic type to be a class and support new()?
我正在嘗試為 Cosmos DB Gremlin Graph API 數據源實現 GenericRepository 模式。 所以我有:
TEntity
,其中TEntity
是class
。 我也這樣做了。錯誤類型“typename”必須是具有公共無參數構造函數的非抽象類型,以便將其用作泛型類型或方法“generic”中的參數“parameter”
在定義泛型類型時,您可以應用多個泛型約束,如下所示:
public class GenericRepository<TEntity> : IGenericRespository<TEntity>
where TEntity : class, new() //the new() constraint must come last
這些約束意味着,為了使類型與GenericRespository<>
一起使用,它必須既是 class(引用類型) ,又必須提供公共無參數構造函數。 (見文檔)
在實踐中,這意味着你可以有一個GenericRepository<object>
,但不是GenericRepository<int>
因為 int 是一個值類型,或者GenericRepository<Uri>
因為雖然Uri
是一個 class,但它沒有一個 public parameter-less構造函數。
public class GenericRespository<T>
where T : class, new()
{
public T Create() => new T();
}
public class Repositories
{
//won't compile, int is a value type;
readonly GenericRespository<int> intRepository = new GenericRespository<int>();
//wont compile, Uri is a class, but no public
//parameterless constructor
readonly GenericRespository<Uri> uriRpository = new GenericRespository<Uri>(); //no public parameterless constructor, doesn't work.
//object is a class and supports new object(), so this works
readonly GenericRespository<object> objectRepository = new GenericRespository<object>(); //works fine
}
這些類型約束意味着您的GenericRespository<TEntity>
將能夠自行創建新的TEntity
實例。 這樣做的真正價值在於,您將能夠創建自己的類並創建它們的存儲庫,而無需編寫任何額外的代碼。
正確答案是 Generics 可以有多個子句。 所以我能夠簡單地通過擴展子句 ( , new()
) 來解決我的問題。 現在TEntity
必須是class
和new()
這對我有好處!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.