简体   繁体   English

检查对象是否使用通用接口实现接口 <T> 泛型类型是T的子代

[英]Checking if an object implements an interface with a generic <T> where the generic type is a child of T

I'm trying to check if a given object implements an interface I made that takes a generic parameter. 我正在尝试检查给定的对象是否实现了我采用通用参数的接口。

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

    void CopyCase(T caseToCopy, T copiedCase);
}

One of my objects implements the interface like this: 我的一个对象实现了这样的接口:

public class ProcessLoad : ElectricalLoad, ICaseCopier<ProcessCase>

Where ProcessCase is a child of ModelElement. 其中ProcessCase是ModelElement的子级。 I have many objects that use that interface with different parameters in the generic, so checking them one by one is out of the question. 我有许多对象在泛型中使用具有不同参数的该接口,因此不可能一一检查它们。

What I tried is this: 我试过的是:

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

But I get the following error: 但是我收到以下错误:

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

ProcessCase is castable to ModelElement. ProcessCase可转换为ModelElement。

You can't do this since the conversion isn't safe - if it were you could do the following: 您不能执行此操作,因为此转换不安全-如果是这样,则可以执行以下操作:

public class OtherElement : ModelElement { }

ICaseCopier<ModelElement> copier = this as ICaseCopier<ProcessCase>;
copier.Case1 = new OtherElement();

The only way you can do this is to make the ICaseCopier<T> interface covariant, which you can't do in its current form since T appears in both input and output positions. 唯一的方法是使ICaseCopier<T>接口协变,由于T出现在输入和输出位置,所以您不能以其当前形式进行协变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我不能将一个项目转换为泛型类型——其中泛型类型是一个接口,并且在检查该项目是否实现了所述接口之后? - Why can't I cast an item to a generic type — where the generic type is an interface, and after checking that the item implements said interface? T实现接口的通用方法<T> - Generic method where T implements Interface<T> 通用方法,其中 T 是实现接口的列表 - Generic Method where T is List that implements interface T型通用接口,其中 - Generic Interface with Type T and where 测试对象是否为任何泛型类型实现通用接口 - Test whether an object implements a generic interface for any generic type 上载到接口 <Foo> 当类实现通用接口时 <T> 类型约束为T = Foo? - Upcasting to an Interface<Foo> when a class implements generic Interface<T> with type constraint T=Foo? 检查我的对象是否在C#中实现了通用接口 - Checking if my object implements a generic interface in C# 除非T实现接口I,否则需要通用方法返回类型T,在这种情况下,返回I - Need generic method to return type T unless T implements interface I, in which case return I 检查类是否实现了泛型接口 - Checking Whether Class Implements Generic Interface 在C#中如何获取不同的IEqualityComparer <T> 泛型类型实现接口的实例 - In C# how to get different IEqualityComparer<T> instance if generic type implements an interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM