不要認爲標題可以解釋我在說什麼,並且解釋有點困難,所以我會讓代碼進行交談。你可以複製+粘貼到LINQPad並作爲C#程序運行它,或者在Visual Studio中作爲常規C#項目進行必要的調整(例如:將調用轉換爲Dump()到Console.Writeline()等) -即使它實現了所需的接口,通用對象仍然需要投射
請注意,如果您取消註釋doStuff方法中的行,它將不會編譯。
我的問題是,爲什麼當generic2已經實現Iab<TA,TB>
時我需要投射?這是一些協變的東西嗎?我仍然在.NET 3.5上。
void Main()
{
doStuff<a,b>();
}
public void doStuff<TA, TB>()
where TA : class, Ia, new()
where TB : class, Ib, new()
{
Iab<TA, TB> x = null;
x = new generic1<TA, TB>();
x.Go().Dump();
//x = new generic2<TA>(); // <-Cannot implicitly convert type 'UserQuery.generic2<TA>' to 'UserQuery.Iab<TA,TB>'. An explicit conversion exists (are you missing a cast?)
x = (Iab<TA, TB>) new generic2<TA>();
x.Go().Dump();
}
public interface Ia
{}
public interface Ib
{}
public class a : Ia
{}
public class b : Ib
{}
public interface Iab<TA,TB>
where TA : class, Ia, new()
where TB : class, Ib, new()
{
string Go();
}
public class generic1<TA, TB> : Iab<TA,TB>
where TA : class, Ia, new()
where TB : class, Ib, new()
{
public string Go()
{
return "generic Base called";
}
}
public class generic2<TA> : Iab<TA,b>
where TA : class, Ia, new()
{
public string Go()
{
return "generic Sub called";
}
}
啊,是的,當然。錯過了那一個:)謝謝! –