In the web.config file, we see a lot of strings following this pattern:
type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup,
System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"
I want to read this information from the web.config (which I know how to read as a string), and I want to instantiate a type from this string.
Is there some way to do this?
Update
I guess I could just do
Activator.CreateInstance(System.GetType(stringTypeName))
Please confirm?
There are several overloads of Activator.CreateInstance
that enable you to do this. However, you will have to split the string into a type name and assembly name manually.
Update: Your own take on this is also correct (although the method is Type.GetType()
).
It's simple to create an instance of a type using Activator.CreateInstance(Type)
.
Edit For some reason I though you could just pass the type name - you can't; thanks Jon for pointing this out.
But you need to get the Type
from the type name. If the type name is always fully-qualified (at least down to the assembly name) - then you can simply use:
Type t = Type.GetType(typeName);
However, that throws an exception if the type can't be found. You might be better off with:
Type t = Type.GetType(typeName, false);
And then:
object result = null;
if(t != null)
result = Activator.CreateInstance(t);
End edit
However, in some cases that type might not have a default constructor, in which case you either have to skip it (you either catch an exception from Activator.CreateInstance
, or do a reflection search for the constructor first), or find a way to build the dependant types as well ( Activator.CreateInstance
supports constructors with parameters too - @Jon's answer includes a link).
I don't believe this simple (Type)
overload I suggest here works with types with constructors that have all-optional parameters, either:
public class MyClass {
public MyClass(string p1 = null, int p2 = 10, ...) { }
}
//...
var o = Activator.CreateInstance(typeof(MyClass)); //<-- will fail
Because that's not a default constructor - it's up to a compiler to bind such constructors as if they were defaults, by pulling out all the default values into a call to the 'expanded' version.
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.