c# – 类型不能在泛型类型或方法中用作类型参数“T” – 为什么?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 类型不能在泛型类型或方法中用作类型参数“T” – 为什么?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2349字,纯文字阅读大概需要4分钟。
内容图文
![c# – 类型不能在泛型类型或方法中用作类型参数“T” – 为什么?](/upload/InfoBanner/zyjiaocheng/794/e1cae3f44af643358680b823c4fd9a38.jpg)
参见英文答案 > Why does a generic type constraint result in a no implicit reference conversion error? 5个
我正在尝试从接口继承两个不同的模型.这些模型应该作为List或Collection传递给Method.现在我收到此错误消息:
The type 'InheritanceTest.FooModel' cannot be used as type parameter 'T' in the generic type or method 'InheritanceTest.Service.DoSomethingWith<T>(System.Collections.Generic.IEnumerable<T>)'. There is no implicit reference conversion from 'InheritanceTest.FooModel' to 'InheritanceTest.IModel<InheritanceTest.IModelItem>'. C:\Work\InheritanceTest\InheritanceTest\Program.cs 14 13 InheritanceTest
有人可以解释一下,我做错了什么? :d
演示代码:
interface IModel<T> where T : IModelItem
{
string Name { get; set; }
IEnumerable<T> Items { get; set; }
}
interface IModelItem
{
string Name { get; set; }
}
class FooModel : IModel<FooModelItem>
{
public FooModel()
{
Items = new List<FooModelItem>();
}
public string Name { get; set; }
public IEnumerable<FooModelItem> Items { get; set; }
}
class FooModelItem : IModelItem
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var fooLists = new List<FooModel>();
var barLists = new ObservableCollection<BarModel>();
var service = new Service();
service.DoSomethingWith(fooLists);
service.DoSomethingWith(barLists);
}
}
class Service
{
public void DoSomethingWith<T>(IEnumerable<T> list) where T : IModel<IModelItem>
{
foreach (var model in list)
{
Debug.WriteLine(model.Name);
foreach (var item in model.Items)
{
Debug.WriteLine(item.Name);
}
}
}
}
演示项目可以在GitHub找到:
https://github.com/SunboX/InheritanceTest/blob/master/InheritanceTest/Program.cs
解决方法:
作为为什么你不能这样做的一个例子,想象一下除了FooModel和FooModelItem之外,你还有BarModelItem.现在让我们说你这样做:
IModel<FooModelItem> fooModel = new FooModel();
IModel<IModelItem> iModel = fooModel;
iModel.Items = new List<BarModelItem>(new BarModelItem());
FooModelItem fooModelItem = fooModel.Items.First();
如果这是有效的代码,你就会遇到麻烦,因为你在最后一行找回的项目实际上不是FooModelItem而是BarModelItem!
如果仔细阅读每一行,您将看到唯一可能的错误行是第二行.这证明了为什么IModel< FooModelItem>不能分配给IModel< IModelItem>,即使FooModelItem:IModelItem.无法执行该分配正是您的方法调用失败的原因.
您可以查看通用协方差和逆变,以了解在某些情况下如何避免这种情况,但在不修改模型的情况下,它对您的特定情况无效.
内容总结
以上是互联网集市为您收集整理的c# – 类型不能在泛型类型或方法中用作类型参数“T” – 为什么?全部内容,希望文章能够帮你解决c# – 类型不能在泛型类型或方法中用作类型参数“T” – 为什么?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。