您当前的位置: 首页 >  c#

幻世界

暂无认证

  • 0浏览

    0关注

    237博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【c#编程技术总结】反射Reflect各种类型方法调用 测试

幻世界 发布时间:2019-04-25 14:17:20 ,浏览量:0

欢迎加入Unity业内qq交流群:956187480

qq扫描二维码加群

 

#region 模块信息
// **********************************************************************
// Copyright (C) 2019 Blazors
// Please contact me if you have any questions
// File Name:             Reflect
// Author:                romantic
// WeChat||QQ:            at853394528 || 853394528 
// **********************************************************************
#endregion
using System;
using System.Reflection;
using UnityEngine;

public class Reflect : MonoBehaviour {

	// Use this for initialization
	void Start () {
        Type type = typeof(ReflectTest);
        object reflectTest = Activator.CreateInstance(type);

        //不带参数且不返回值的方法的调用  
        MethodInfo methodInfo = type.GetMethod("MethodWithNoParaNoReturn");
        methodInfo.Invoke(reflectTest, null);


        //不带参数且有返回值的方法的调用  
        methodInfo = type.GetMethod("MethodWithNoPara");
        string tt = methodInfo.Invoke(reflectTest, null).ToString();
        Debug.LogWarning(tt);


        //带参数且有返回值的方法的调用  
        methodInfo = type.GetMethod("Method1", new Type[] { typeof(string) });
         string ss = methodInfo.Invoke(reflectTest, new object[] { "测试" }).ToString();
        Debug.LogWarning(ss);


        //带多个参数且有返回值的方法的调用  
        methodInfo = type.GetMethod("Method2", new Type[] { typeof(string), typeof(int) });
        string str =  methodInfo.Invoke(reflectTest, new object[] { "测试", 100 }).ToString();
        Debug.LogWarning(str);

        //静态方法的调用  
        methodInfo = type.GetMethod("StaticMethod");
        string strr = methodInfo.Invoke(null, null).ToString();
        Debug.LogWarning(strr);
    }
}
public class ReflectTest
{
    public void MethodWithNoParaNoReturn()
    {
        Debug.Log("调用不带参数且无返回值的方法");
    }

    public string MethodWithNoPara()
    {
        Debug.Log("调用不带参数且有返回值的方法");
        return "MethodWithNoPara";
    }

    public string Method1(string str)
    {
        Debug.Log("调用带参数且有返回值的方法");
        return "我是返回值: "+str;
    }

    public string Method2(string str, int index)
    {
        Debug.Log("调用带多参数且有返回值的方法");
        return "我是返回值: "+str + index.ToString();
    }

    public static string StaticMethod()
    {
        Debug.Log("调用静态方法");
        return "我是返回值: "+"StaticMethod";
    }
}

欢迎加入Unity业内qq交流群:956187480

qq扫描二维码加群

关注
打赏
1660704426
查看更多评论
立即登录/注册

微信扫码登录

0.0360s