好的,為了簡化我們有兩個類: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);
}
所以當我實作這個類并最終解決泛型時,在一個好的情況下:
public class RepositoryA<A,String> : IRepository<T, TKey>{
public String getKey(A entity)=> A.key;
}
但在 B 情況下顯然不是,因為 int 不是物件,所以我做了一個類 int 包裝器:
public class RepositoryB<B,IntWrapper> : IRepository<B, IntWrapper>{
public String getKey(B entity)=> B.key;
}
Int 包裝器只是一個 int 值的容器。
public class IntWrapper{
int value;
}
所以問題是:我可以指出這樣的事情嗎???
public interface IRepository<T,TKey> where T: class where TKey:class|nonclassvalue
或者在不欺騙 IntWrapper 的情況下做我正在做的事情的正確方法是什么?
與此問題相關:
c# where for generic type constraint class may not be
c#泛型約束哪里不是類?
uj5u.com熱心網友回復:
所以問題是:我可以指出這樣的事情嗎???
public interface IRepository<T,TKey> where T: class where TKey:class|nonclassvalue
當然,只需TKey完全洗掉約束:
public interface IRepository<T,TKey> where T: class
uj5u.com熱心網友回復:
無限制地使用TKey它
public interface IRepository<T,TKey>
where T: class
沒有TKey:class|nonclassvalue
uj5u.com熱心網友回復:
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;
}
這是你想要的?
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/449171.html
上一篇:在通用類激活器上找不到建構式
下一篇:呼叫T方法并將結果轉換為字串C#
