Creating an instance of variable with reflection
I want to create an instance of type t with reflection, that is
Type t = typeof(string);
string s = (t)Activator.CreateInstance(t); // this fails because of convertion
string s = Activator.CreateInstance(t) as t // als开发者_如何学Goo fails
Is there a way to perform such a convertion? Thanks.
Yes. You have to convert to string
, not to t
. You may want a generic method, alternatively:
public T GetInstance<T>()
{
Type t = typeof(T);
T s = (T)Activator.CreateIstance(t);
return s;
}
As things stand you are attempting to cast an object that is actually an instance of System.String
to type System.Type
...
Try this:
string s = (string)Activator.CreateInstance(t);
Activator.CreateInstance returns an instance boxed in an object so it must be cast to the correct type before you can use it.
In your example t is a Type object variable and not a type reference. You must either specify the type directly as in my example or you can use generics.
精彩评论