简体   繁体   中英

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.

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:

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:

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:

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

Int wrapper just a container of the int value.

 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?

related with this questions:

c# where for generic type constraint class may NOT be

c# generic constraint where is not 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:

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

Just use it without the TKey constraint

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

Without the 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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