[英]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.