Analysis of reflection examples in C #
Today, I would like to share with you the relevant knowledge points of reflection instance analysis in C#. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article, let's take a look at it.
1. Get the assembly Assembly
1. Get the currently running assembly
System.Reflection.Assembly [] asm = AppDomain.CurrentDomain.GetAssemblies (); / / Assembly b = Assembly.GetExecutingAssembly ()
2. Get the assembly of the specified file: the Load,LoadFrom,LoadFile method.
Assembly c = Assembly.Load ("mscorlib.dll"); / / if you refer to the program and, then go straight to the Load () method, and the assembly name can be loaded in the parameters. Assembly c = Assembly.Load ("mscorlib"); Assembly d = Assembly.LoadFrom (AppDomain.CurrentDomain.BaseDirectory + "mscorlib.dll"); / / LoadFrom can only be used to load assemblies with different identities, that is, unique assemblies, and cannot be used to load assemblies with the same identity but different paths. Assembly e = Assembly.LoadFile (AppDomain.CurrentDomain.BaseDirectory + "mscorlib.dll"); / / LoadFile: only the specified file is loaded, but the dependent assembly is not automatically loaded. 2. Get the type Type (referring to the Class class): Assembly asm = Assembly.GetExecutingAssembly (); Type [] tArr = asm.GetExportedTypes (); / / get the public types defined in the assembly
1. Get the Type object from the class string: Assembly.GetType ("), Module.GetType ("), Type.GetType ("")
Assembly ass = Assembly.LoadFrom (@ "C:\ bin\ Debug\ ConsoleApplication2.exe"); Console.WriteLine (ass.GetType ("ConsoleApplication2.Person"). ToString (); / / get ClassModule mod = ass.GetModules () [0] from the assembly (dll or exe); Console.WriteLine (mod.GetType ("ConsoleApplication2.Person"). ToString (); Type type = Type.GetType ("System.Int32") / / static method. Parameter is fully qualified name (preferred) Type type = Type.GetType ("MyAssembly.Example", false,true) / / Note 0 is the class name. Parameter 1 indicates whether an exception is thrown if the corresponding class is not found. Parameter 2 indicates whether the class name is case-sensitive.
2. Get the Type object from the concrete class: the typeof operator
Type T4 = typeof (TestSpace.TestClass); / / use the typeof operator
3. Get the Type object from the instance: Object.GetType ()
Example example = new Example (); Type type = example.GetType (); Type T3 = 42.GetType (); / / get the type based on the object instance
4. Attributes of Type
Get the member MemberInfoMemberInfo [] miArr = t.GetMembers (BindingFlags.Instance | BindingFlags.Public); / / instance and public members. And BindingFlags.Static | BindingFlags.NonPublicforeach (MemberInfo item in miArr) {bool a = item is FieldInfo; PropertyInfo; MethodBase; ConstructorInfo; MethodInfo; EventInfo; Type;} t.GetConstructor (); / / get constructor t.GetFields (); / / get field t.GetProperties (); / / get attribute t.GetMethods (); / / get method t.GetEvents (); / / get event t.GetInterfaces (); / / get interface t.GetCustomAttributes (true) / / get the custom attributes marked on the type
Contains several classes commonly used for reflection within the System.Reflection namespace:
Assembly: this class allows you to load and manipulate an assembly and get the internal information of the assembly
EventInfo: this class holds the given event information
FieldInfo: this class holds the given field information
MethodInfo: this class holds the given method information
MemberInfo: this class is a base class that defines multiple common behaviors of EventInfo, FieldInfo, MethodInfo, and PropertyInfo
Module: this class allows you to access a given module in multiple assemblies
ParameterInfo: this class holds the given parameter information
PropertyInfo: this class holds the given attribute information
4. Get the specific member Type t = Assembly.GetExecutingAssembly (). GetType ("TestSpace.TestClass"); MethodInfo m = t.GetMethod ("TestMethod"); ParameterInfo [] p = m.GetParameters (); / / obtain method parameters 5. Create an instance
1. Create a type instance based on Assembly: asm.CreateInstance ()
Assembly asm = Assembly.GetExecutingAssembly (); TestClass obj = asm.CreateInstance ("TestSpace.TestClass"); / / create Assembly instance 2, create instance based on type: Activator.CreateInstance () Type t = Type.GetType ("TestSpace.TestClass"); TestClass obj = (TestClass) Activator.CreateInstance (t); / / 1, create instance based on type TestClass obj = (TestClass) Activator.CreateInstance (t, new object [] {"aa"}) / / 2. Create an instance / / TestClass obj = (TestClass) t.InvokeMember ("TestClass", BindingFlags.CreateInstance, null, null, null) according to the "constructor with parameters"; VI. Call method
1. Call the instance method: Invoke
MethodInfo m = t.GetMethod ("WriteString"); object returnValue = m.Invoke (obj, new object [] {"test", 1}); / / pass two parameters. If the method has no parameters, you can set the second parameter of Invoke to null// or object returnValue = m.Invoke (obj, BindingFlags.Public, Type.DefaultBinder, new object [] {"test", 1}, null); / / the last parameter represents Culture.
2. Call static method
MethodInfo m = t.GetMethod ("StaticMethod"); object returnValue = m.Invoke (null, new object [] {"test", 1}); VII. Reflection attribute
The attributes in the class can be found through System.Reflection.Property. The commonly used methods are GetValue (object,object []) to obtain attribute values and SetValue (object,object,object []) to set attribute values.
PropertyInfo propertyName = type.GetProperty ("Name"); / / get the Name attribute object propertyName.SetValue (obj, "Zhang Fei", null); / / set the value of the Name property object objName = propertyName.GetValue (obj, null); / / get the attribute value
Set the value of the property according to the type of the property
Type type = typeof (Person); / / Note to enter all paths, including the namespace object obj = Activator.CreateInstance (type); / / assume that this is the data Dictionary dic = new Dictionary (); dic.Add ("Id", "1"); dic.Add ("Name", "Warriors"); 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); / / when different types of values need to be set for attributes}} Person person = obj as Person;Console.WriteLine (person.Birthday); VIII. Reflection characteristics
The features in a class can be reflected through System.Reflection.MemberInfo 's GetCustomAttributes (Type,bool).
Assembly assembly = Assembly.Load ("fanshe"); Type type = assembly.GetType ("fanshe.Person"); / / Note to enter all paths, including the namespace object obj = Activator.CreateInstance (type); object [] typeAttributes = type.GetCustomAttributes (false); / / get the property of the Person class foreach (object attribute in typeAttributes) {Console.WriteLine (attribute.ToString ()) / / output System.SerializableAttribute because I added a [Serializable]} IX to Person. Create delegated instance TestDelegate myDelegate = (TestDelegate) Delegate.CreateDelegate (typeof (TestDelete), obj, "MyMethod"); string returnValue = myDelegate ("Hello"); / / execute delegation 10. Application examples
1. Dynamically load assemblies
Assembly asm = Assembly.LoadFrom (@ "E:\ Test.dll"); Type type = asm.GetType ("TestSpace.TestClass"); object obj = System.Activator.CreateInstance (type); / / you can also use cast to convert obj to a predefined interface or abstract class (such as Form), directly executing the base method without reflecting GetMethod .MethodInfo m = type.GetMethod ("WriteString"); m.Invoke (obj, new object [] {"test"})
2. Get the T type in List:
List dogs = new List (); Type type = dogs.GetType (); if (type.IsGenericType) {Type [] genericArgTypes = type.GetGenericArguments (); if (genericArgTypes [0] = = typeof (Dog)) {/ / is that what you want to judge? }} above is all the content of this article "reflection instance Analysis in C#". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.