C#类型转换错误,尽管通用约束

C#类型转换错误,尽管通用约束,第1张

概述为什么,对于“必须从A继承”的类P的类型参数T的通用约束,第一次调用成功但第二次调用失败,注释中详细说明了类型转换错误: abstract class A { }static class S{ public static void DoFirst(A argument) { } public static void DoSecond(ICollection<A> argume 为什么,对于“必须从A继承”的类P的类型参数T的通用约束,第一次调用成功但第二次调用失败,注释中详细说明了类型转换错误:

abstract class A { }static class S{    public static voID DoFirst(A argument) { }    public static voID DoSecond(ICollection<A> argument) { }}static class P<T>    where T : A,new(){    static voID Do()    {        S.DoFirst(new T());             // this call is OK        S.DoSecond(new List<T>());      // this call won't compile with:        /* cannot convert from 'System.Collections.Generic.List<T>'           to 'System.Collections.Generic.ICollection<A>' */    }}

通用约束不应该确保List< T>.确实是ICollection< A>?

解决方法 这是C#在泛型类型上缺少 covariance的一个例子(C#确实支持数组协方差). C#4将在接口类型上添加此功能,并且还将更新多个BCL接口类型以支持它.

请参阅C# 4.0: Covariance and Contravariance:

In this article I’ll try to cover one of the C# 4.0 innovations. One of the new features is covariance and contravariance on type parameters that is Now supported by generic delegates and generic interfaces. First let’s see what does these words mean 总结

以上是内存溢出为你收集整理的C#类型转换错误,尽管通用约束全部内容,希望文章能够帮你解决C#类型转换错误,尽管通用约束所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1215493.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存