本文介绍了为什么我不能转换Foo< Bar>到IFoo< IBar>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么不能将 Foo< Bar>
转换为 IFoo< IBar>
.
如果我尝试我会得到:
推荐答案
如果您使用的是C#4,并且 IFoo
被声明为:
It would work if you were using C# 4 and IFoo
were declared as:
public interface IFoo<out T>
假设 Bar
实现 IBar
,而 Foo< T>
实现 IFoo< T>
.
但是,只有在安全的情况下才可以这样声明.如果 T
值进入" API并出现,那是不安全的.例如:
However, it could only be declared that way if it were safe. It's not safe if T
values "go into" the API as well as coming out. For example:
public interface IFoo<T>
{
T Value { get; set; }
}
此不能在T中是协变的,否则您可以这样写:
This can't be covariant in T, as otherwise you could write:
public class StringFoo : IFoo<string>
{
public T Value { get; set; }
}
IFoo<string> fooString = new StringFoo(); // That's fine
IFoo<object> fooObject = fooString; // This isn't, because...
fooObject.Value = new Object(); // ... this would violate type safety
阅读Eric Lippert的关于泛型方差的长博客系列有关更多信息.
Read Eric Lippert's long blog series on generic variance for much more information.
这篇关于为什么我不能转换Foo< Bar>到IFoo< IBar>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!