今天來講一講《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;