Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C#中,如何判断泛型类型T是否(不是实现!)是接口?_C#_Generics_Types_Interface - Fatal编程技术网

在C#中,如何判断泛型类型T是否(不是实现!)是接口?

在C#中,如何判断泛型类型T是否(不是实现!)是接口?,c#,generics,types,interface,C#,Generics,Types,Interface,编辑:我犯了一个错误,前提是错误的。正如前面所指出的,iClass确实可以工作,就像typeof(T)IsInterface一样 假设我有这个方法: public T GetService<T>() where T : IService public T GetService(),其中T:IService 我想测试泛型类型T是否作为接口而不是类发送到此方法中。换句话说,我想区分来自MyClass.GetService()和MyClass.GetService()的调用。我该怎么做

编辑:我犯了一个错误,前提是错误的。正如前面所指出的,iClass确实可以工作,就像typeof(T)IsInterface一样

假设我有这个方法:

public T GetService<T>() where T : IService
public T GetService(),其中T:IService
我想测试泛型类型T是否作为接口而不是类发送到此方法中。换句话说,我想区分来自
MyClass.GetService()
MyClass.GetService()
的调用。我该怎么做

我尝试使用
is object
,而
is System.object
,但它不会做出这种区别。使用
typeof(T).IsClass
default(T).IsClass
也不起作用,分别是因为System.Type返回类型始终是一个类,并且因为IsClass对默认的T不可用


我还能怎么做呢?

原来我的前提是错的。这确实有效:

typeof(T).IsClass

如果指定了接口,则返回false。

我认为您可以像下面这样检查运行时

typeof(T).IsInterface

有关更多详细信息。

我测试了您的案例,typeof(T)。IsClass确实有效

您是否尝试过简单的强制转换,然后检查是否为null?在您的情况下,对象T应该始终实现IService,否则将引发编译器异常。所以我不理解你的问题,我并不是想弄清楚t是否实现了接口;我想防止类的用户使用实现调用此方法-他们应该使用接口返回类型。