【问题标题】:Checking if an object implements an interface with a generic <T> where the generic type is a child of T检查对象是否使用泛型 <T> 实现接口,其中泛型类型是 T 的子级
【发布时间】:2013-02-20 03:03:11
【问题描述】:

我正在尝试检查给定对象是否实现了我制作的采用通用参数的接口。

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

    void CopyCase(T caseToCopy, T copiedCase);
}

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

public class ProcessLoad : ElectricalLoad, ICaseCopier<ProcessCase>

其中 ProcessCase 是 ModelElement 的子级。我有许多对象在泛型中使用具有不同参数的接口,因此无法一一检查它们。

我尝试的是这样的:

ICaseCopier<ModelElement> copier = this as ICaseCopier<ProcessCase>;

但我收到以下错误:

Cannot convert source type 'ICaseCopier<ProcessCase>' to target type 'ICaseCopier<ModelElement>'

ProcessCase 可转换为 ModelElement。

【问题讨论】:

    标签: c# generics inheritance


    【解决方案1】:

    您不能这样做,因为转换不安全 - 如果是,您可以执行以下操作:

    public class OtherElement : ModelElement { }
    
    ICaseCopier<ModelElement> copier = this as ICaseCopier<ProcessCase>;
    copier.Case1 = new OtherElement();
    

    您可以做到这一点的唯一方法是使ICaseCopier&lt;T&gt; 接口协变,因为T 出现在输入和输出位置,所以您不能以其当前形式做到这一点。

    【讨论】:

    • 我明白了,这是有道理的......所以最好的方法是将我的属性中的 'T' 替换为 'ModelElement' 或 CopyCase 方法?
    • @AdamSmith - 我不确定你的意思 - 如果你的意思是让你的界面非通用,那么这是一种可能性。否则,您也许可以将代码重组为具有只读接口并使用其他机制进行复制。
    • 谢谢,我在搜索“协变”后找到了我想要的东西。感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2017-04-06
    • 2012-11-28
    • 2017-01-21
    • 2013-08-16
    • 1970-01-01
    • 2013-08-29
    相关资源
    最近更新 更多