使用反射创建变量实例 [英] Creating an instance of variable with reflection

查看:49
本文介绍了使用反射创建变量实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用反射创建一个类型为t的实例,即<预><代码>类型 t = typeof(string);字符串 s = (t)Activator.CreateInstance(t);//由于转换而失败string s = Activator.CreateInstance(t) as t//也失败

有没有办法执行这样的转换?谢谢.

解决方案

是的.您必须转换为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...

这篇关于使用反射创建变量实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆