C#Generic Interfaces转换问题

lko*_*lko 2 .net c# generics

应该使用c#4和VS 2010吗?我正在对实现通用接口的类进行一些处理,并且在处理之后想要将对象转换为更简单的接口,因此我可以提取由公共接口定义的某些属性.

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; }
}
Run Code Online (Sandbox Code Playgroud)

例如,这个类有ClassX和ClassY,我希望它们是某些类型的处理/保存,但之后我只想提取像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;
}
Run Code Online (Sandbox Code Playgroud)

的铸造x上述(t1t2属性特异性)的更简单的IMyInterface接口出现故障.

有很多通用的界面问题,但我没有看到(或认出?)任何解决方案.

Ant*_*hyy 5

您正在寻找的解决方案称为方差(协方差和逆变).但是你IMyInterface不能作出任何协变或逆变中T1T2,因为它具有公共getter和setter方法公众接受T1T2:

interface IAnimal {}
class Dog : IAnimal { public void Bark () ; }
class Cat : IAnimal { public void Meow () ; }

var dogs = new FileImpl<Dog, Dog> () ;
dogs.t1  = new Dog () ;

var file = (IFile<IAnimal, IAnimal>) dogs ; // if this were OK...
file.t1  = new Cat () ;                     // this would have to work
dogs.t1.Bark () ;                           // oops, t1 is a cat now
Run Code Online (Sandbox Code Playgroud)