SoFunction
Updated on 2025-03-07

Reflection in C#

1. Get assembly assembly

1. Get the currently running assembly

[] asm = ();
 //
Assembly b = ();

2. Get the assembly of the specified file: Load, LoadFrom, LoadFile methods.

Assembly c = ("");//If you reference the program and then directly load() method, and the assembly name in the parameter can be loaded.  Assembly c = ("mscorlib");Assembly d = ( + "");//LoadFrom can only be used to load assembly with different identities, that is, unique assembly, and cannot be used to load assembly with the same identities but different paths.Assembly e = ( + "");//LoadFile:Load only the specified file,But the dependency assembly will not be loaded automatically

2. Get type Type (referring to Class class):

Assembly asm = ();
Type[] tArr = ();//Get the common type defined in the assembly

1. Obtain Type objects from class strings: (""), (""), ("")

Assembly ass = (@"C:\bin\Debug\");
(("").ToString());    //Get the Class inside according to the assembly (dll or exe)
Module mod = ()[0];
(("").ToString());   

Type type = ("System.Int32");// Static method, parameter is fully qualified name (preferred)Type type = ("",false,true)   //Notice0It's a class name,parameter1Indicates whether an exception is thrown if the corresponding class cannot be found,parameter2Indicates whether the class name is case sensitive

2. Obtain Type object from concrete class: typeof operator

Type t4 = typeof();//usetypeofOperators

3. Obtain Type object from the instance: ()

Example example = new Example();
Type type = ();

Type t3 = ();//Get type based on object instance

4. Type properties

;
;
;
;

3. Obtain member MemberInfo

MemberInfo[] miArr = ( | );//Instances and public members.  And |foreach (MemberInfo item in miArr)
{
    bool a = item is FieldInfo;
    PropertyInfo;
    MethodBase;
    ConstructorInfo;
    MethodInfo;
    EventInfo;
    Type;
}

();//Get the constructor();//Get the field(); //Get attribute();//Get method();//Get Event();//Get the interface(true);//Get custom properties marked on type

Contains multiple commonly used classes for reflection in the namespace:

  • Assembly: This class can load and manipulate an assembly and obtain 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 given modules in multiple assembly settings
  • ParameterInfo: This class holds the given parameter information
  • PropertyInfo: This class holds the given property information

4. Obtain specific members

Type t = ().GetType("");
MethodInfo m = ("TestMethod");
ParameterInfo[] p = ();//Get method parameters

5. Create an instance

1. Create type instances based on Assembly: ()

Assembly asm = ();
TestClass obj = ("");//according toAssemblyCreate type instance

2. Create an instance according to the type: ()

Type t = ("");
TestClass obj = (TestClass)(t);//1. Create an instance based on the typeTestClass obj = (TestClass)(t, new object[] { "aa" });// 2. Create an instance based on "Constructor with Parameters"//
TestClass obj = (TestClass)("TestClass", , null, null, null);

6. Calling methods

1. Call the instance method: Invoke

MethodInfo m = ("WriteString");
object returnValue = (obj, new object[] { "test", 1 });//Transfer two parameters. If the method has no parameters, you can set the second parameter of Invoke to null//orobject returnValue = (obj, , , new object[] { "test", 1 }, null);//The last parameter indicatesCulture.

2. Call static methods

MethodInfo m = ("StaticMethod");
object returnValue = (null, new object[] { "test", 1 });

7. Reflection properties

You can find the properties in the class by searching. Common methods are GetValue(object, object[]) to get the attribute value and SetValue(object, object, object[]) to set the attribute value.

PropertyInfo propertyName = ("Name");    //Get Name attribute object(obj, "Zhang Fei", null);                //Set the value of Name propertyobject objName = (obj, null);  //Get attribute value

Set the value of the attribute according to the type of the attribute

Type type = typeof(Person);      //Note that you need to enter all paths, including namespaceobject obj = (type);
//Suppose this is data that exists in XMLDictionary<string, string> dic = new Dictionary<string, string>();
("Id", "1");
("Name", "Samurai of God");
("Birthday", "2001-01-01");

PropertyInfo[] ProArr = ();
foreach (PropertyInfo p in ProArr)
{
    if (())
    {
        (obj, (dic[], ), null);  //When you need to set different types of values ​​for attributes    }
}

Person person = obj as Person;
();

8. Reflection characteristics

GetCustomAttributes(Type,bool) can reflect the characteristics in a class.

Assembly assembly = ("fanshe");
Type type = ("");      //Note that you need to enter all paths, including namespaceobject obj = (type);
object[] typeAttributes = (false);       //Get the features of Person classforeach (object attribute in typeAttributes)
{
    (());    //Output Because I added a [Serializable] to Person}

9. Create a delegate instance

TestDelegate myDelegate = (TestDelegate)(typeof(TestDelete), obj, "MyMethod");
string returnValue = myDelegate("Hello");//Execution Delegation

10. Application examples

1. Dynamic loading of assembly

Assembly asm = (@"E:\");
Type type = ("");
object obj = (type);//You can also use cast to convert obj into a predefined interface or abstract class (such as Form), and directly execute the base method without reflecting GetMethod.MethodInfo m = ("WriteString");
(obj, new object[] { "test" });

2. Obtain the T type in List<T>:

List&lt;Dog&gt; dogs = new List&lt;Dog&gt;();
Type type = ();
if ()
{
Type[] genericArgTypes = ();
if (genericArgTypes[0] == typeof(Dog))
{
//Is this what you want to judge?}
}

This is all about this article about C# reflection. I hope it will be helpful to everyone's learning and I hope everyone will support me more.