检查对象是否实现了泛型<T>的接口,其中泛型类型是T的子级

Ada*_*ith 0 c# generics inheritance

我正在尝试检查给定对象是否实现了我接受泛型参数的接口.

public interface ICaseCopier<T> where T : ModelElement 
{
    T Case1 { get; set; }
    T Case2 { get; set; }

    void CopyCase(T caseToCopy, T copiedCase);
}
Run Code Online (Sandbox Code Playgroud)

我的一个对象实现了这样的接口:

public class ProcessLoad : ElectricalLoad, ICaseCopier<ProcessCase>
Run Code Online (Sandbox Code Playgroud)

ProcessCase是ModelElement的子代.我有很多对象在泛型中使用具有不同参数的接口,因此逐个检查它们是不可能的.

我试过的是这个:

ICaseCopier<ModelElement> copier = this as ICaseCopier<ProcessCase>;
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

Cannot convert source type 'ICaseCopier<ProcessCase>' to target type 'ICaseCopier<ModelElement>'
Run Code Online (Sandbox Code Playgroud)

ProcessCase可以转换为ModelElement.

Lee*_*Lee 5

您无法执行此操作,因为转换不安全 - 如果是,您可以执行以下操作:

public class OtherElement : ModelElement { }

ICaseCopier<ModelElement> copier = this as ICaseCopier<ProcessCase>;
copier.Case1 = new OtherElement();
Run Code Online (Sandbox Code Playgroud)

唯一可以做到这一点的方法是使ICaseCopier<T>界面协变,因为它T出现在输入和输出位置,所以它不能以当前形式进行.