문제

I have a project I am working on that I would like to leverage Activator.createInstance with so that I can dynamically pull class names out of XML. The classes must subscribe to at least one of two interfaces depending on their functionality. My question is, when I use Activator.CreateInstance, what is the best way to tell which interface the class I've instantiated subscribes to? Should I wrap the cast in a try catch? It seems like that would be awful slow. Maybe I should cast it an obj and then call GetType and compare that to my interface names? Any help is appreciated!

도움이 되었습니까?

해결책

So you've already created the object? Then it's as simple as using as the is operator.

var obj = Activator.CreateInstance(...);
bool objIsIMyInterface = obj is IMyInterface;

If you'd like to test at the point you've created a System.Type, you can use Type.IsAssignableFrom:

Type type = ...
bool typeIsIMyInterface = typeof(IMyInterface).IsAssignableFrom(type);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top