Resolve type of generic T to a specific interface in C#
我想找到通用T的类型,并将其进行比较,以在运行时检查它是哪个接口。
因此,这可以在运行时找到t的类型:
1
| Type interfaceName = typeof(T ); // gives me the specific interface type |
但是当我试图检查它是否等于接口的类型时,我没有得到预期的响应。
1
| Type.GetType("IMyInterface"); //this returns null |
号
我如何比较这两者?
- 请看:stackoverflow.com/questions/4963160/…
- @尝试去证明这不是我想要的。此外,我不想在代码的这一部分使用反射。
如果要使用Type.GetType,需要传递程序集限定名。
但是,看起来您只是想检查接口的名称,因此您可以简单地使用
1 2
| Type interfaceType = typeof(T );
string interfaceName = interfaceType .Name; |
号
您也可以简单地检查一下typeof(T) == typeof(IMyInterface)是否
- "Simply check to see if typeof(t)=typeof(imyinterface)"would be the correct answer all by itself.
- The first solution would result in fals positives if there were an interface with the same name elsewhere.The second solution would be uldn't pass if the type is some type that implements or extends the interface.
- @Servy fair point on the first solution,it's a straightforward fix to the original post.但是,就第二个问题而言,问题国"我想确定性别的类型,并比较这一点,即要检查什么样的界面是,在运行时间"-不是什么接口这一工具或扩展。
- @Alexg do you think he really means that or,do you think he did't know t he correct terminology to explain what he really want?
- @Servy I would uldn't expule to know;if that is the case then the question can be closed as a duplicate of the one linked by trying toimprove
- @Alexg thanks that worked!
- @Servy:Alex read it right.我想检查一下接口类型。
- @servy oh and by the way,this is she,not he.Just saying:
GetType方法需要完全限定名。所以你需要:
1
| Type.GetType("YourNamespace.IMyInterface"); |
或者,如果您有一个对声明IMyInterface的程序集的引用,那么只有typeof(IMyInterface)可以完成这项工作。
可能是这样的:
1
| typeof(T ).Name =="IMyInterface" |