Pergunta

I understand that C# is a staticly typed language and I already read the answers to this SO posting: initialize a class by string variable in c#?

My question is a bit different, however. I'm working with a T4 template that provides me with the name of a class as a string parameter. I would give the template code here but what's important is that the type is in a string, so it's the same as having this statement in any C# module:

string s = "MyNamespace.Customer.Model";

Using that string, I need to get the type into a Type variable. Normally, I would use this code when I have access to the actual type:

Type typeModel = typeof(MyNamespace.Customer.Model);

How would I be able to obtain the Type given a string? In other words, my code would ideally look something like this (I know this doesn't work because "s" is a string):

Type typeModel = typeof(s);

(I do know what assembly the type is in, by the way, so I can use that information; also, the assembly containing the Type in question is referenced by the template, for what that's worth...)

Note: I do not want to create an object instance of the Type so please don't suggest a solution that requires using Activator.CreateInstance unless that's the only solution...

Thank you for any ideas you can provide.

Foi útil?

Solução

The method Type.GetType(string typeName) does what you want, but if you only provide the FullName (namespace and name) of the type, it will only resolve types from the current assembly or mscorlib.

You would need to supply an AssemblyQualifiedName if you want to resolve types outside the current assembly. The problem of course is that multiple assemblies can contain different types with the same name and namespace (thanks Steven Liekens):

string aqn = Assembly.CreateQualifiedName(assemblyName, namespaceAndNameOfType);
Type t = Type.GetType(aqn);

If you don't know the assembly beforehand, you could deal with this by:

And then iterating over each assembly's GetTypes() method.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top