首页 / C# / c#Generics“in”关键字
c#Generics“in”关键字
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c#Generics“in”关键字,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2302字,纯文字阅读大概需要4分钟。
内容图文
![c#Generics“in”关键字](/upload/InfoBanner/zyjiaocheng/795/e60c4bea70c4438ca7a7a57c59a75b66.jpg)
我最近被分配到现有应用程序的一些维护工作.我遇到过以下代码:
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#Generics“in”关键字全部内容,希望文章能够帮你解决c#Generics“in”关键字所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。