Вопрос

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