Conversion error with generic covariance

自古美人都是妖i 提交于 2019-12-12 19:23:39

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/22051322/conversion-error-with-generic-covariance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!