C#知识点讲解之C#反射技术

今天来讲一讲《C#知识点讲解之C#反射》

一、通过C#反射技术,两种方法获取类实例(本程序集内)

namespace MyReflection
{
	//测试使用类
    public class ReflectionTest
    {
        public int port;
        public int Port { get; set;}

        public string ip;

        public void StartConnect(string ip, int port)
        {
            Debug.Log("Start connect, ip: " + ip + "\t port: " + port );
        }
    }

    public class Reflection : MonoBehaviour
    {
        // Start is called before the first frame update
        void Start()
        {
            //1,通过类名获取类的实例
            string className = "Water.ReflectionTest";
            Type type1 = Type.GetType(className);
            object obj = type1.Assembly.CreateInstance(className);
            
            //获取类的字段以及它的值
            FieldInfo fi1 = type1.GetField("port");
            Debug.Log("field info : " + fi1.Name + "\t value: " + Convert.ToInt32(fi1.GetValue(obj)));

            //获取类的属性以及它的值
            PropertyInfo property1 = type1.GetProperty("Port");
            Debug.Log(property1.GetValue(obj));

            //获取类的方法以及传参调用
            MethodInfo method1 = type1.GetMethod("StartConnect");
            method1.Invoke(obj, new object[]{"172.0.0.1", 8080});

            Debug.Log("-----------------------------------------------------------------------------");
            //2,通过指定类获取类的实例
            ReflectionTest rt = new ReflectionTest();
            Type type2 = typeof(ReflectionTest);

            //获取类的字段以及它的值
            FieldInfo fi2 = type2.GetField("port");
            Debug.Log("file info:" + fi2.Name + "\t value: " + Convert.ToInt32(fi2.GetValue(rt)));

            //获取类的属性以及它的值
            PropertyInfo property2 = type2.GetProperty("Port");
            Debug.Log(property2.GetValue(rt));

            //获取类的方法以及传参调用
            MethodInfo method2 = type2.GetMethod("StartConnect");
            method2.Invoke(rt, new object[]{"172.0.0.1", 8080});
        }
    }
}

输出:
在这里插入图片描述

二、跨程序集访问

分两种情况:(此处转载自:https://blog.csdn.net/szy759590387/article/details/96287654)

1、需要加载的程序集已经在程序中被引用了,则直接从当前程序域中查找即可:

Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.GetName().Name.Contains("theAssemblyName"));

2、需要加载的程序集未被加载,则使用程序集名称加载:

Assembly assembly = Assembly.Load(@"theAssemblyName, Version=55.0.0.0, Culture=neutral, PublicKeyToken=ef0f902af9dee505");

Tips:如何获取dll文件的PublicKeyToken,Culture,Version:

Assembly assembly = Assembly.LoadFile(@"C:\Program Files\ReferencedAssemblies\theAssemblyName.dll");
string name = assembly.FullName;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章