具有通用协方差的转换误差 [英] Conversion error with generic covariance

查看:94
本文介绍了具有通用协方差的转换误差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 无法从'UserQuery.SomeClass< int>'转换到UserQuery.Interface< System.IConvertible>'

代码:

  void Main()
{
List< Interface< IConvertible>> values = new List< Interface< IConvertible>>();
values.Add(new SomeClass< int>(){Value = 50});
}

interface Interface< out T> T:IConvertible
{
T Value {get; }
}
class SomeClass< T> :接口< T> T:IConvertible
{
public T Value {get;组;然而,试图添加 SomeClass< string>以及>

工作正常。

  values.Add(new SomeClass< string>(){Value =50 }); 

任何人都可以请解释我为什么可以为字符串做,但不是int和double等...

解决方案

我在这里找到了答案:
这是C#4中的协变错误吗?



通常,值类型不支持差异。这就是为什么它不能用于int,但对字符串有效。


I got the following code and it gives me compile error:

cannot convert from 'UserQuery.SomeClass<int>' to UserQuery.Interface<System.IConvertible>'

the code:

void Main()
{
    List<Interface<IConvertible>> values = new List<Interface<IConvertible>>();
    values.Add(new SomeClass<int>() {Value = 50 });
}

interface Interface<out T> where T : IConvertible
{
   T Value { get; }
}
class SomeClass<T> : Interface<T> where T : IConvertible
{
   public T Value { get; set; }
}

However, trying to add SomeClass<string> works fine.

values.Add(new SomeClass<string>() {Value = "50" });

Could anyone please explain me why I can do it for string, but not for int nor double and so on...

解决方案

I've found the answer here: Is this a covariance bug in C# 4?

Generally, variance is not supported for value types. That's why it won't work for int, but does work for string.

这篇关于具有通用协方差的转换误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆