似乎我在.NET-2.0 / unity的.NET-2.0中发现了一个奇怪的错误。
public class Test
{
public interface ICovariant<out T>
{
T GetT();
}
public class Covariant<T>: ICovariant<T>
{
public T GetT()
{
throw new NotImplementedException();
}
}
public interface IFoo
{
}
public class Bar : IFoo
{
}
public class CovariantHolder
{
public CovariantHolder(ICovariant<IFoo> covariant)
{
}
}
public class CovariantBar: Covariant<Bar>
{
}
public static void Main(string[] args)
{
ICovariant<IFoo> foo = new Covariant<IFoo>();
ICovariant<IFoo> foobar = new Covariant<Bar>();
ICovariant<IFoo> bar = new CovariantBar();
CovariantBar barbar = new CovariantBar();
new CovariantHolder(foo); // works
new CovariantHolder(foobar); // works
new CovariantHolder(bar); // works
new CovariantHolder(barbar); // works
Console.WriteLine(typeof(ICovariant<IFoo>).IsAssignableFrom(typeof(Covariant<IFoo>))); // true;
Console.WriteLine(typeof(ICovariant<IFoo>).IsAssignableFrom(typeof(Covariant<Bar>))); // true;
Console.WriteLine(typeof(ICovariant<IFoo>).IsAssignableFrom(typeof(CovariantBar))); // false! what?;
typeof(CovariantHolder).GetConstructors()[0].Invoke(new object[] {foo}); //works
typeof(CovariantHolder).GetConstructors()[0].Invoke(new object[] {foobar}); //fails! WHAAT?
typeof(CovariantHolder).GetConstructors()[0].Invoke(new object[] {bar}); //fails!
typeof(CovariantHolder).GetConstructors()[0].Invoke(new object[] {barbar}); //fails!
}
}
AFAIK,unity使用mono 2.0.50727.1433
周围有什么办法吗?我可以使用协变参数通过反射来设置对象吗?
UPD :
错误代码:
InvalidCastException: Value is not a convertible object: Test+Covariant``1[GameInstaller+Bar] to Test+ICovariant``1[[Test+IFoo, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]