![](/img/trans.png)
[英]C# generic class type parameter and constraint that is the same as the generic parameter
[英]c# generic constraint when T is class or primitive type
好的,為了簡化我們有兩個類:A,B:兩個類都有一個主鍵,稱為鍵。
public class A{
String key;
}
public class B{
int key;
}
所以我們有一個接口來管理我稱之為 IRepository 的所有實體,對於這個例子只有 1 個操作:
public interface IRepository<T,TKey> where T: class wher Y:class {
TKey getKey(T entity);
}
所以當我實現這個 class 並最終解析 generics 時,在一個很好的案例中:
public class RepositoryA<A,String> : IRepository<T, TKey>{
public String getKey(A entity)=> A.key;
}
但在 B 情況下顯然不是,因為 int 不是 object,所以我做了一個 class int 包裝器:
public class RepositoryB<B,IntWrapper> : IRepository<B, IntWrapper>{
public String getKey(B entity)=> B.key;
}
Int wrapper 只是一個 int 值的容器。
public class IntWrapper{
int value;
}
所以問題是:我可以指出這樣的事情嗎???
public interface IRepository<T,TKey> where T: class where TKey:class|nonclassvalue
或者在不欺騙 IntWrapper 的情況下做我正在做的事情的正確方法是什么?
與這個問題相關:
所以問題是:我可以指出這樣的事情嗎???
public interface IRepository<T,TKey> where T: class where TKey:class|nonclassvalue
當然,只需完全刪除對TKey
的約束:
public interface IRepository<T,TKey> where T: class
只需在沒有TKey
約束的情況下使用它
public interface IRepository<T,TKey>
where T: class
沒有TKey:class|nonclassvalue
public interface IRepository<T, TKey>
{
TKey getKey(T entity);
}
public class RepositoryA: IRepository<A, string>
{
public string getKey(A entity) {
return entity.key;
}
}
public class RepositoryB: IRepository<B, int>{
public int getKey(B entity)=> entity.key;
}
這是你想要的?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.