简体   繁体   English

c# T 为 class 或原始类型时的泛型约束

[英]c# generic constraint when T is class or primitive type

Ok, to simplify we have 2 classes:A,B: both clases have a primary key, called key.好的,为了简化我们有两个类:A,B:两个类都有一个主键,称为键。

public class A{
String key;
}

public class B{
int key;
}

So we have an interface to manage all entities i called it IRepository, and for this example has only 1 operation:所以我们有一个接口来管理我称之为 IRepository 的所有实体,对于这个例子只有 1 个操作:

public interface IRepository<T,TKey> where T: class wher Y:class {
    TKey getKey(T entity);
}

So when i implement this class and finally resolving the generics, in A case good:所以当我实现这个 class 并最终解析 generics 时,在一个很好的案例中:

public class RepositoryA<A,String> : IRepository<T, TKey>{
 public String getKey(A entity)=> A.key;
}

But in B case obviously not, because int is not an object, so i did a class int wrapper:但在 B 情况下显然不是,因为 int 不是 object,所以我做了一个 class int 包装器:

public class RepositoryB<B,IntWrapper> : IRepository<B, IntWrapper>{
public String getKey(B entity)=> B.key;
}

Int wrapper just a container of the int value. Int wrapper 只是一个 int 值的容器。

 public class IntWrapper{
       int value;
    }

So the question is: can i indicate something like this???所以问题是:我可以指出这样的事情吗???

public interface IRepository<T,TKey> where T: class where TKey:class|nonclassvalue 

Or what is the correct way to do what im doing without tricking IntWrapper?或者在不欺骗 IntWrapper 的情况下做我正在做的事情的正确方法是什么?

related with this questions:与这个问题相关:

c# where for generic type constraint class may NOT be c# 其中对于泛型类型约束 class 可能不是

c# generic constraint where is not class? c# 通用约束哪里不是 class?

So the question is: can i indicate something like this???所以问题是:我可以指出这样的事情吗???

public interface IRepository<T,TKey> where T: class where TKey:class|nonclassvalue

Sure, just remove the constraint on TKey altogether:当然,只需完全删除对TKey的约束:

public interface IRepository<T,TKey> where T: class

Just use it without the TKey constraint只需在没有TKey约束的情况下使用它

public interface IRepository<T,TKey> 
where T: class

Without the TKey:class|nonclassvalue没有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;
}

Is this what you are looking for?这是你想要的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM