網站首頁 編程語言 正文
一、獲取程序集Assembly
1、獲取當前運行的程序集
System.Reflection.Assembly[] asm = AppDomain.CurrentDomain.GetAssemblies();
//
Assembly b = Assembly.GetExecutingAssembly();
2、獲取指定文件的程序集:Load,LoadFrom,LoadFile方法。
Assembly c = Assembly.Load("mscorlib.dll");//如果你引用了程序及,那么就直接Load()方法,參數里面程序集名稱就可以加載了。Assembly c = Assembly.Load("mscorlib");
Assembly d = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "mscorlib.dll");//LoadFrom只能用于加載不同標識的程序集, 也就是唯一的程序集, 不能用于加載標識相同但路徑不同的程序集。
Assembly e = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "mscorlib.dll");//LoadFile:只加載指定文件,但不會自動加載依賴程序集
二、獲取類型Type (指Class類):
Assembly asm = Assembly.GetExecutingAssembly();
Type[] tArr = asm.GetExportedTypes();//獲取程序集中定義的公共類型
1、從類字符串中獲得Type對象:Assembly.GetType(“”),Module.GetType(“”), Type.GetType(“”)
Assembly ass = Assembly.LoadFrom(@"C:\bin\Debug\ConsoleApplication2.exe");
Console.WriteLine(ass.GetType("ConsoleApplication2.Person").ToString()); //根據程序集(dll或exe)獲取里面的Class
Module mod = ass.GetModules()[0];
Console.WriteLine(mod.GetType("ConsoleApplication2.Person").ToString());
Type type = Type.GetType("System.Int32");//靜態方法,參數為完全限定名(首選)
Type type = Type.GetType("MyAssembly.Example",false,true) //注意0是類名,參數1表示若找不到對應類時是否拋出異常,參數2表示類名是否區分大小寫
2、從具體類中獲得Type對象:typeof運算符
Type t4 = typeof(TestSpace.TestClass);//使用typeof運算符
3、從實例中獲得Type對象:Object.GetType()
Example example = new Example();
Type type = example.GetType();
Type t3 = 42.GetType();//根據對象實例獲取類型
4、Type的屬性
t.IsPublic;
t.IsAbstract;
t.IsClass;
t.IsValueType;
三、獲取成員MemberInfo
MemberInfo[] miArr = t.GetMembers(BindingFlags.Instance | BindingFlags.Public);//實例與公共成員。還有BindingFlags.Static|BindingFlags.NonPublic
foreach (MemberInfo item in miArr)
{
bool a = item is FieldInfo;
PropertyInfo;
MethodBase;
ConstructorInfo;
MethodInfo;
EventInfo;
Type;
}
t.GetConstructor();//獲取構造函數
t.GetFields();//獲取字段
t.GetProperties(); //獲取屬性
t.GetMethods();//獲取方法
t.GetEvents();//獲取事件
t.GetInterfaces();//獲取接口
t.GetCustomAttributes(true);//獲取類型上標記的自定義屬性
在System.Reflection命名空間內包含多個反射常用的類:
- Assembly: 通過此類可以加載操縱一個程序集,并獲取程序集內部信息
- EventInfo: 該類保存給定的事件信息
- FieldInfo :該類保存給定的字段信息
- MethodInfo :該類保存給定的方法信息
- MemberInfo :該類是一個基類,它定義了EventInfo、FieldInfo、MethodInfo、PropertyInfo的多個公用行為
- Module :該類可以使你能訪問多個程序集中的給定模塊
- ParameterInfo :該類保存給定的參數信息
- PropertyInfo: 該類保存給定的屬性信息
四、獲取具體成員
Type t = Assembly.GetExecutingAssembly().GetType("TestSpace.TestClass");
MethodInfo m = t.GetMethod("TestMethod");
ParameterInfo[] p = m.GetParameters();//獲取方法參數
五、創建實例
1、根據Assembly創建類型實例:asm.CreateInstance()
Assembly asm = Assembly.GetExecutingAssembly();
TestClass obj = asm.CreateInstance("TestSpace.TestClass");//根據Assembly創建類型實例
2、根據類型創建實例:Activator.CreateInstance()
Type t = Type.GetType("TestSpace.TestClass");
TestClass obj = (TestClass)Activator.CreateInstance(t);//1、根據類型創建實例
TestClass obj = (TestClass)Activator.CreateInstance(t, new object[] { "aa" });// 2、根據”有參數的構造函數”創建實例
//
TestClass obj = (TestClass)t.InvokeMember("TestClass", BindingFlags.CreateInstance, null, null, null);
六、調用方法
1、調用實例方法:Invoke
MethodInfo m = t.GetMethod("WriteString");
object returnValue = m.Invoke(obj, new object[] { "test", 1 });//傳兩參數,若方法無參數,可以將Invoke的第二個參數設為null
//或者
object returnValue = m.Invoke(obj, BindingFlags.Public, Type.DefaultBinder, new object[] { "test", 1 }, null);//最后一個參數表示Culture.
2、調用靜態方法
MethodInfo m = t.GetMethod("StaticMethod");
object returnValue = m.Invoke(null, new object[] { "test", 1 });
七、反射屬性
通過System.Reflection.Property能查找到類里面的屬性。 常用的方法有GetValue(object,object[])獲取屬性值和SetValue(object,object,object[])設置屬性值
PropertyInfo propertyName = type.GetProperty("Name"); //獲取Name屬性對象
propertyName.SetValue(obj, "張飛", null); //設置Name屬性的值
object objName = propertyName.GetValue(obj, null); //獲取屬性值
根據屬性的類型設置屬性的值
Type type = typeof(Person); //注意要輸入全部路徑,包括命名空間
object obj = Activator.CreateInstance(type);
//假設這是存在于XML的數據
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("Id", "1");
dic.Add("Name", "神靈武士");
dic.Add("Birthday", "2001-01-01");
PropertyInfo[] ProArr = type.GetProperties();
foreach (PropertyInfo p in ProArr)
{
if (dic.Keys.Contains(p.Name))
{
p.SetValue(obj, Convert.ChangeType(dic[p.Name], p.PropertyType), null); //當需要給屬性設置不同類型的值時
}
}
Person person = obj as Person;
Console.WriteLine(person.Birthday);
八、反射特性
通過System.Reflection.MemberInfo的GetCustomAttributes(Type,bool)就可反射出一個類里面的特性。
Assembly assembly = Assembly.Load("fanshe");
Type type = assembly.GetType("fanshe.Person"); //注意要輸入全部路徑,包括命名空間
object obj = Activator.CreateInstance(type);
object[] typeAttributes = type.GetCustomAttributes(false); //獲取Person類的特性
foreach (object attribute in typeAttributes)
{
Console.WriteLine(attribute.ToString()); //輸出 System.SerializableAttribute 因為我在Person上里加了個[Serializable]
}
九、創建委托實例
TestDelegate myDelegate = (TestDelegate)Delegate.CreateDelegate(typeof(TestDelete), obj, "MyMethod");
string returnValue = myDelegate("Hello");//執行委托
十、應用舉例
1、動態加載程序集
Assembly asm = Assembly.LoadFrom(@"E:\Test.dll");
Type type = asm.GetType("TestSpace.TestClass");
object obj = System.Activator.CreateInstance(type);//也可以使用強制轉換,將obj轉換為預定義的接口或者抽象類(如Form),直接執行基方法,不用反射GetMethod .
MethodInfo m = type.GetMethod("WriteString");
m.Invoke(obj, new object[] { "test" });
2、獲得List<T>中的T類型:
List<Dog> dogs = new List<Dog>();
Type type = dogs.GetType();
if (type.IsGenericType)
{
Type[] genericArgTypes = type.GetGenericArguments();
if (genericArgTypes[0] == typeof(Dog))
{
//你想要判斷的是這個嗎?
}
}
原文鏈接:https://www.cnblogs.com/springsnow/p/9433924.html
相關推薦
- 2021-12-03 Android消息機制Handler深入理解_Android
- 2022-05-01 Android?模擬地圖定位功能的實現_Android
- 2023-12-24 npm安裝element ui出錯的問題--版本不匹配
- 2022-10-01 React?Hook中useState更新延遲問題及解決_React
- 2022-11-07 PostgreSQL常用優化技巧示例介紹_PostgreSQL
- 2022-05-11 使用kettle的數據庫增量備份與全量備份
- 2023-01-09 React應用框架Dva數據流向原理總結分析_React
- 2022-11-16 C++實現中綴轉后綴的示例詳解_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支