首先,先随便创建一个测试类
<span style="font-family:Microsoft YaHei;font-size:18px;">public class ABC
{
public void test1()
{
Debug.Log("test111");
}
public void test2()
{
Debug.Log("test2222");
}
}</span>下面是利用反射技术,将字符串转化为类名并遍历类中所有方法(我是在Unity中进行测试的,在C#其他项目中调用也是一样的)
<span style="font-family:Microsoft YaHei;font-size:18px;">public class NewBehaviourScript : MonoBehaviour {
// Use this for initialization
void Start () {
string aa = "ABC";</span><span style="font-family:Microsoft YaHei;font-size:18px;"> Type t;
t = Type.GetType(aa);
var obj = t.Assembly.CreateInstance(aa);
<span style="white-space:pre"> </span>//var obj = System.Activator.CreateInstance(t);
MethodInfo[] info = t.GetMethods();
for (int i = 0; i < info.Length; i++)
{
info[i].Invoke(obj, null);
}
}</span>这么调用将会报出参数数量不匹配的错误,如图:
我们加入下面几行代码,就会恍然大悟。
<span style="font-family:Microsoft YaHei;font-size:18px;"> Debug.Log("方法数量:" + info.Length);
for (int i = 0; i < info.Length; i++)
{
string str = info[i].Name;
Debug.Log("方法名:" + str);
}</span>大家注意,反射出来的方法数量其实不是2个,而是6个,C#反射自带了4个方法,分别是Equals,GetHashCode,GetType,ToString方法,如图,打印结果为:
如果不想遍历全部方法的话,也可以指定方法名进行调用,添加如下代码即可
<span style="font-family:Microsoft YaHei;font-size:18px;"> MethodInfo method = t.GetMethod("test2");
method.Invoke(obj, null);</span>
本文通过实例演示如何使用C#反射技术将字符串转化为类名,并遍历类中的所有方法。介绍了反射过程中可能出现的问题及解决方法,包括指定方法名进行调用。
7864

被折叠的 条评论
为什么被折叠?



