简体   繁体   English

通过Activator.CreateInstance检查对象是否为接口

[英]Check if Object is Interface via Activator.CreateInstance

I am using Activator.CreateInstance to create an object from a Dll at run time, 我正在使用Activator.CreateInstance在运行时从Dll创建对象,

If the object is an Interface I get an error and I don't want to create an object of that interface. 如果对象是接口,则会出现错误,并且我不想创建该接口的对象。

So my question is there any option to check if an object is Interface and not class? 所以我的问题是,有什么选择可以检查对象是否是接口而不是类?

As I don't want to reply to each answer separately, you should use type.IsAbstract instead of type.IsInterface, because you don't want to fire off an activator on an abstract class either (and .IsAbstract covers interfaces too). 因为我不想分别回答每个答案,所以应该使用type.IsAbstract而不是type.IsInterface,因为您也不想在抽象类上触发激活器(而且.IsAbstract也涵盖了接口)。 You may not have run into this problem yet but it is certainly a potential issue. 您可能尚未遇到此问题,但它肯定是潜在问题。

Do you mean you want to check if a type is an interface type? 您是否要检查类型是否为接口类型? If so, that's easy: 如果是这样,那很简单:

if (type.IsInterface)

If you mean "is this object of a type which implements any interfaces" it's still feasible, but harder and probably less useful... 如果您的意思是“此对象是实现任何接口的类型的对象”,它仍然是可行的,但更困难,而且用途可能更少。

you can do this: 你可以这样做:

Type t = obj.GetType();
t.IsInterface()

Would this help? 这会有所帮助吗?

Type t = typeof(T);
if (t.IsInterface) {
} else {
}

By the way, you state that you do not want to create an object that is an interface. 顺便说一句,您声明您不想创建作为接口的对象。 It is not possible to do that of cause; 这是不可能做到这一点的原因的; however, you can instantiate classes and define structs that implement interfaces. 但是,您可以实例化类并定义实现接口的结构。

var obj = new MyClass();  // OK
var s = new MyStruct();  // OK
var i = new IMyInterface(); // NOT POSSIBLE!

Interfaces have no implementation. 接口没有实现。 They are a contract that classes and structs must fulfill when they pretend to implement the interface. 它们是类和结构假装实现接口时必须履行的契约。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM