编程语言
首页 > 编程语言> > c#Generics“in”关键字

c#Generics“in”关键字

作者:互联网

我最近被分配到现有应用程序的一些维护工作.我遇到过以下代码:

public interface IEntityService<T, in TKey>
{
    T GetEntityById(TKey id);    
    IEnumerable<T> GetAll();    
    void Update(T entity);    
    void Delete(TKey key);
}

我不确定in关键字对第二个泛型参数TKey的作用.

我遇到了以下MSDN文章,它应该完美地向我解释:
in (Generic Modifier) (C# Reference)

但是,我并不是真的了解它.这就是它所说的:

For generic type parameters, the in keyword specifies that the type
parameter is contravariant. You can use the in keyword in generic
interfaces and delegates.

Contravariance enables you to use a less
derived type than that specified by the generic parameter. This allows
for implicit conversion of classes that implement variant interfaces
and implicit conversion of delegate types. Covariance and
contravariance in generic type parameters are supported for reference
types, but they are not supported for value types.

A type can be
declared contravariant in a generic interface or delegate if it is
used only as a type of method arguments and not used as a method
return type. Ref and out parameters cannot be variant.

An interface
that has a contravariant type parameter allows its methods to accept
arguments of less derived types than those specified by the interface
type parameter. For example, because in .NET Framework 4, in the
IComparer interface, type T is contravariant, you can assign an
object of the IComparer(Of Person) type to an object of the
IComparer(Of Employee) type without using any special conversion
methods if Employee inherits Person.

A contravariant delegate can be
assigned another delegate of the same type, but with a less derived
generic type parameter.

我认为这是有道理的,但特别引用

Contravariance enables you to use a less derived type than that
specified by the generic parameter.

如何对int进行任何使用?是否有任何“衍生类型”我会传入?

解决方法:

我注意到int的唯一引用是在你的问题的最后一行.你确定IEntityService<>是仅用于int键吗?可能它是为Compound Key构建的(主键由多列组成)

现在,在NHibernate中,对于复合键,您使用整个类来表示它们,因此您可以使用表MyTable a

class MyTableKey 
{ 
    public int Code;
    public int SubCode;
}

如果您有一个辅助表MuSubtable连接到该表,那么您可以拥有

class MySubtableKey : MyTableKey 
{
    public int SubSubCode; 
}

其中MySubtable是一个表,其主键是MyTable(代码子代码)的完整主键加上另一个字段(SubSubCode).

标签:c,contravariance,generics
来源: https://codeday.me/bug/20190623/1273567.html