Why can I not convert a Foo<Bar> to IFoo<IBar>
Why can I not convert a Foo<Bar>
to IFoo<I开发者_开发问答Bar>
.
If I try I get:
There is no implicit reference conversion from
Foo<Bar>
toIFoo<IBar>
It would work if you were using C# 4 and IFoo
were declared as:
public interface IFoo<out T>
assuming that Bar
implements IBar
and Foo<T>
implements IFoo<T>
.
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; }
}
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
Read Eric Lippert's long blog series on generic variance for much more information.
In order for this to work, three things need to be true:
Bar
must implementIBar
Foo
must implementIFoo
IFoo<T>
must be covariant inT
(like this:IFoo<out T>
)
It depends on the version of C# you are compiling with.
Generic covariance and contravariance was introduced with C# and .NET 4: http://msdn.microsoft.com/en-us/library/dd799517.aspx
精彩评论