且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用反射创建变量实例

更新时间:2023-11-15 11:57:28

是的.您必须转换为string,而不是t.您可能需要一个通用方法,或者:

public T GetInstance(){类型 t = typeof(T);T s = (T)Activator.CreateIstance(t);返回 s;}

就目前情况而言,您正试图将一个实际上是 System.String 实例的对象强制转换为类型 System.Type...

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.

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