![](/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.