這應該可以使用C#4和VS 2010嗎?我正在對實現通用接口的類進行一些處理,並且在處理之後想要將對象轉換爲更簡單的接口,以便我可以提取由通用接口定義的某些屬性。C#通用接口鑄造問題
interface IMyInterface
{
public Id { get; set; }
}
interface IFile<T1, T2> where T1 : IMyInterface where T2 : IMyInterface
{
Int64 prop1 { get; set; }
T1 t1 { get; set; }
T2 t2 { get; set; }
}
ClassA : IMyInterface
{
... Implement some properties plus interface
public Id { get; set; }
}
ClassB : IMyInterface
{
... Implement some properties plus interface
public Id { get; set; }
}
例如,這類有ClassX和優雅的,我想是某些類型的用於處理/保存,但是在那之後我只要提取等的ID,其是常見的實現此通用的所有類之間的共同屬性接口(其他屬性是不常見的在T1,T1)
ClassSomething : IFile<ClassA, ClassB>
{
... Implement properties plus interface
public ClassX t1
{ get {} set {} }
public ClassY t2
{ get {} set {} }
}
IList<IFile<TItem1, TItem2>> list = new List<IFile<TItem1, TItem2>>()
ClassA ca = new ClassA();
... Fill in the interface defined properties
... Fill the list with objects of ClassSomething
foreach (IFile<TItem1, TItem2> x in list)
{
// This fails
IFile<IMyInterface, IMyInterface> interfaceItem =
(IFile<IMyInterface, IMyInterface>)x;
}
的x
上述(t1
和t2
性質特異性)的流延到簡單IMyInterface
接口出現故障。
有很多通用接口問題,但我沒有看到(或認識到)任何解決方案。
你可能需要看看c#4.0的協方差和反變化 – ca9163d9
哇,快速和好看的答案。我需要採取一些並消化答案。 :) – lko
偉大的答案,他們都是有益的,我會選擇一個基於普遍投票的答案。 (我<3 SO) – lko