c#与具有泛型类型的接口类型进行转换

时间:2013-04-05 09:22:03

标签: c# generics interface casting

我有一个实现接口MockRepository的类IRepository,我有一个实现接口Technology的类IIdentifiable

我想将一个对象从MockRepository<Technology>转换为IRepository<IIdentifiable>,并在一些操作完成后再次强制转换。这可能吗?我的代码编译但当我尝试运行它时,我得到一个无效的强制转换异常。

2 个答案:

答案 0 :(得分:3)

简短的回答是否定的。

如果您有一个接口IMyInterface<T>,那么编译器将为您使用的每种类型的T创建一个新接口,并替换T的所有值。

举个例子:

我有一个界面:

public interface IMyInterface<T> {
   public T Value {get; set;}
}

我有2个班级:

public class Foo {}

public class Bar : Foo {}

然后我定义以下

public class Orange : IMyInterface<Foo> {}

public class Banana : IMyInterface<Bar> {}

编译器将使用特定的名称约定自动创建2个新接口,我将使用不同的名称来突出显示它们是不同的

public interface RandomInterface {
   Foo Value { get; set; }
}

public interface AlternativeInterface {
   Bar Value { get; set; }
}

public class Orange : RandomInterface {
}

public class Banana : AlternativeInterface {
}

正如您所看到的,RandomInterfaceAlternativeInterface之间没有任何关系。因此,从RandomInterface继承的类无法转换为AlternativeInterface

阅读问题评论后更新

如果您希望将MockRepository传递给期望IRepository的函数,您可以执行以下操作

 public void MyFunction<T>(IRepository<T> repo) where T: IIdentifiable {
 }

答案 1 :(得分:0)

我认为你有:

class MockRepository<T> : IRepository<T>  // note: same T
{
}

interface IRepository<out X>  // note: "out" means covariance in X
{
}

然后因为TechnologyIIdentifiable,协方差表明IRepository<Technology>也是IRepository<IIdentifiable>

因此,如果您的IRepository<>接口是(或可以制作)协变的,那么它应该有效。