我有一個屬性,如下:演員繼承類型通用
public ITypeA<IType2> MyProperty {
get {
return new ImplementationA<ImplementationB>();
}
}
我怎樣才能做到這一點。 (new ImplementationA<ImplementationB>() as ITypeA<IType2>)
返回null,並且不允許投射。
我有一個屬性,如下:演員繼承類型通用
public ITypeA<IType2> MyProperty {
get {
return new ImplementationA<ImplementationB>();
}
}
我怎樣才能做到這一點。 (new ImplementationA<ImplementationB>() as ITypeA<IType2>)
返回null,並且不允許投射。
您需要使用out
keyword聲明接口的通用參數爲covariant。
你能舉個例子嗎?請注意,這是C#3.5 – hungryMind 2012-02-02 19:42:44
@hungryMind - 我已經在「out」泛型修飾符中添加了MSDN文檔的鏈接,以指向SLaks答案,它包含示例。 @SLaks - 希望你不介意。 – 2012-02-02 19:46:29
我認爲泛型協方差是在C#4.0中引入的。 – 2012-02-02 19:50:19
對於.NET 3.5,我想你最好的選擇是使用wrappr:
class ImplementationWrapper : ITypeA<IType2>
{
public ImplementationA<ImplementationB> MyObject { get; set; }
}
public ITypeA<IType2> MyProperty {
get {
return new ImplementationWrapper {
MyObject = new ImplementationA<ImplementationB>()
};
}
}
如果'ImplementationA''農具ITypeA ',這個工程沒有一個演員。如果它沒有實施,即使演員陣容也不行。我沒有看到你真正想要解決的問題。 –
hvd
2012-02-02 19:43:38