C#:是与继承泛型类型运营商 [英] C#: Is operator for Generic Types with inheritance

查看:127
本文介绍了C#:是与继承泛型类型运营商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与一个问题是运营商比较泛型类型

I have a problem with the is operator comparing generic types.

 public interface ISomeInterface<T> where T : SomeBaseClass{
 }

 public class SomeClass : SomeBaseClass{
 }

现在我们要检查与运营商是类型。我们有一个类实现接口ISomeInterface的一个实例。

Now we want to check the type with is operator. We have an instance of a class implementing interface ISomeInterface.

不幸的是,我们正面临着以下问题:

Unfortunatly we are facing following problem:

 // someObject is an Instance of a class implementing interface ISomeInterface<SomeClass>
 bool isSomeBaseClass = someObject is ISomeInterface<SomeBaseClass>; // false
 bool isSomeClass = someObject is ISomeInterface<SomeClass>; // true



时可以检查变量泛型类型?

Is it possible to check a variable generic type?

在此先感谢,
托比

Thanks in advance, Tobi

推荐答案

这就是所谓的通用协方差和支持C#4.0。你可以标记与退出关键字通用 T 参数:

This is called generic covariance and is supported in C# 4.0. You could mark the generic T parameter with the out keyword:

public interface ISomeInterface<out T> where T : SomeBaseClass

这有一个限制,但。在 T 参数只能出现在接口中的方法返回类型。

This has a limitation though. The T parameter can only appear as return type of the methods in the interface.

埃里克利珀有一个<一个HREF =htt​​p://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/default.aspx相对=nofollow>系列博客文章对这个问题的,我请您阅读。

Eric Lippert has a series of blog posts on this subject that I invite you to read.

这篇关于C#:是与继承泛型类型运营商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆