I am using Activator.CreateInstance to create an object from a Dll at run time,

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?

有帮助吗?

解决方案

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...

其他提示

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). You may not have run into this problem yet but it is certainly a potential issue.

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归因
不隶属于 StackOverflow
scroll top