简体   繁体   中英

Activate type only without knowing the namespace of the type I am trying to activate

I'm not sure this is possible, and the existing answers to this question seem to imply that you need to know the namespace.

I am trying to activate a type, but would prefer to avoid specifying the Type's namespace. Is this possible? Of course I would know the Assembly ahead of time.

string qualifiedName = Assembly.GetAssembly(typeof(MyType)).FullName;
Type toActivate = Type.GetType("sometype, " + qulifiedName);

I've tried various ways, but hitting road blocks. Seems like I must know the namespace of the type. Is this true? Or am I missing something.

To recap, I have two things...

  1. The name of the type, ie MyClass
  2. Its executing assembl

You can list all types in the current application domain or executing assembly and do a Where to get the type you're looking for.

var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes())

Or

var types = Assembly.GetAssembly(typeof(MyType)).GetTypes()

Followed by:

var myType = types.Where(t => t.Name == nameToFind);

Then you can decide whether a type was found, or if multiple, which one to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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