开发者

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> to IFoo<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:

  1. Bar must implement IBar
  2. Foo must implement IFoo
  3. IFoo<T> must be covariant in T (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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜