当 T 为 class 或原始类型时的 c# 泛型约束
c# generic constraint when T is class or primitive type
好的,为了简化我们有 2 classes: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 并最终解析泛型时,在一个很好的情况下:
public class RepositoryA<A,String> : IRepository<T, TKey>{
public String getKey(A entity)=> A.key;
}
但在 B 情况下显然不是,因为 int 不是对象,所以我做了一个 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 的情况下做我正在做的事情的正确方法是什么?
与此问题相关:
c# generic constraint where is not class?
在没有TKey
约束的情况下使用它
public interface IRepository<T,TKey>
where T: class
没有 TKey:class|nonclassvalue
So the question is: can i indicate something like this???
public interface IRepository<T,TKey> where T: class where TKey:class|nonclassvalue
当然,只需完全取消对 TKey
的限制:
public interface IRepository<T,TKey> where T: class
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;
}
这是您要找的吗?
好的,为了简化我们有 2 classes: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 并最终解析泛型时,在一个很好的情况下:
public class RepositoryA<A,String> : IRepository<T, TKey>{
public String getKey(A entity)=> A.key;
}
但在 B 情况下显然不是,因为 int 不是对象,所以我做了一个 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 的情况下做我正在做的事情的正确方法是什么?
与此问题相关:
c# generic constraint where is not class?
在没有TKey
约束的情况下使用它
public interface IRepository<T,TKey>
where T: class
没有 TKey:class|nonclassvalue
So the question is: can i indicate something like this???
public interface IRepository<T,TKey> where T: class where TKey:class|nonclassvalue
当然,只需完全取消对 TKey
的限制:
public interface IRepository<T,TKey> where T: class
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;
}
这是您要找的吗?