Creating an instance of variable with reflection

时光毁灭记忆、已成空白 提交于 2020-01-16 18:02:06

问题


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 // also fails

Is there a way to perform such a convertion? Thanks.


回答1:


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...




回答2:


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.



来源:https://stackoverflow.com/questions/2012363/creating-an-instance-of-variable-with-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!