Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use reflection mode and delegate mode in C # method

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to use the reflection and delegation methods in the C# method, which is very detailed and has a certain reference value. Friends who are interested must read it!

In the process of development, the static method is called by adding a dot after the type name, followed by the name of the calling method, and the type instance method is called through new an object, followed by the method name, which are the two most familiar ways. You can also use reflection to make method calls by reading CLR metadata. When invoking methods using reflection, the two most important classes are System.Type and System.Reflection.MethodInfo. To call a method with an Invoke method of type MethodInfo, you must pass in a reference to the target object instance. As follows:

PublicclassCalculate {/ / Private method private intAdd (intleftNum, intrightNum) {returnleftNum + rightNum can be called using reflection }} classProgram {staticvoidMain (string [] args) {/ / use the type.getmethod method to obtain the type method, BindingFlags sets the scope of the lookup method / / this example is public method, private method and non-static method is found, if you want to find static method / / you need to set BindingFlags.Static MethodInfomethod = typeof (Calculate) .GetMethod ("Add", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) If (method = = null) return / / call method parameter object [] paras = {10,20}; / / Target object instance: newCalculate () objectresult = method.Invoke (newCalculate (), paras); Console.WriteLine (result); Console.ReadLine ();}}

Entrustment mode

Any object can call a delegate, as long as the method returns a value and the method signature is the same as the delegate declaration.

By reading the CLR source code, we sort out the important fields of the delegate class and several common methods, and the custom delegate types are all derived from MulticastDelegate.

PublicabstractclassDelegate: ICloneable,ISerializable {/ / calls the target object, the instance method is a type instance reference, and the static method is null internalObject_target; / / pointing to the calling method internalIntPtr_methodPtr / / delegate the constructor protectedDelegate (Objecttarget, Stringmethod) {/ / omit, to view the clr source code} publicstaticDelegateCreateDelegate (Typetype, Objecttarget, Stringmethod) {/ / omission, specifically to view the clr source code} publicstaticDelegateCreateDelegate (Typetype, Typetarget, Stringmethod) {/ / omission See the clr source code} publicstaticDelegateCombine (paramsDelegate [] delegates) {} publicstaticDelegateCombine (Delegatea, Delegateb) {} publicstaticDelegateRemove (Delegatesource, Delegatevalue) {}} publicabstractclassMulticastDelegate: Delegate {privateObject_invocationList ProtectedMulticastDelegate (Objecttarget, Stringmethod): base (target, method) {} protectedMulticastDelegate (Typetarget, Stringmethod): base (target, method) {}}

You can see from the source code that the Delegate class provides several overloaded static methods CreateDelegate, and the return value of the method is of type Delegate. Pass the object reference to it if it is an instance method, and pass in the object type if it is a static method.

PublicdelegateintDelegateCaculate (inta,intb); publicclassCaculate {publicintAdd (intnum1, intnum2) {returnnum1 + num2;} publicstaticintSubtract (intnum1, intnum2) {returnnum2-num1;}} classProgram {staticvoidMain (string [] args) {Caculatecaculate = newCaculate (); TypetypeCaculate = typeof (Caculate); TypetypeDelegate = typeof (DelegateCaculate); DelegateCaculateadd = (DelegateCaculate) Delegate.CreateDelegate (typeDelegate, caculate, "Add"); DelegateCaculatesubtract = (DelegateCaculate) Delegate.CreateDelegate (typeDelegate, typeCaculate, "typeCaculate") Console.WriteLine ("add:" + add (10,20)); Console.WriteLine ("subtract:" + subtract (10,20)); Console.ReadLine ();}}

CreateDelegate needs to traverse the metadata to get the method handle. The C # syntax provides a more convenient way to call a delegate. You can simply qualify the method by the type name or object name without having to traverse the metadata. The C# compiler uses the ldftn or ldvirtftn operator of the underlying CIL to obtain the method address, which is much faster than CreateDelegate. The above Main method can be rewritten to

StaticvoidMain (string [] args) {DelegateCaculateadd = newDelegateCaculate (newCaculate () .add); DelegateCaculatesubtract = newDelegateCaculate (Caculate.Subtract); Console.WriteLine ("add:" + add (10,20)); Console.WriteLine ("subtract:" + subtract (10,20)); Console.ReadLine ();}

Multiple delegate objects can be placed in an array of delegate objects, and once called, CLR iterates through the delegate array, calling it one by one.

PublicdelegatevoidDelegateCaculate (inta,intb); publicclassCaculate {publicstaticvoidAdd (intnum1, intnum2) {Console.WriteLine ((num1+ num2));} publicstaticvoidSubtract (intnum1, intnum2) {Console.WriteLine ((num2- num1));}} classProgram {staticvoidMain (string [] args) {DelegateArray (newDelegateCaculate (Caculate.Add), newDelegateCaculate (Caculate.Subtract); Console.ReadLine ();} staticvoidDelegateArray (DelegateCaculatea, DelegateCaculateb) {DelegateCaculatedelChain = null delChain = (DelegateCaculate) Delegate.Combine (delChain, a) DelChain = (DelegateCaculate) Delegate.Combine (delChain, b); delChain (10,20);}}

C # provides a more convenient syntax for adding delegate objects to the delegate array, and you can modify the DelegateArray method above

StaticvoidDelegateArray (DelegateCaculatea, DelegateCaculateb) {DelegateCaculatedelChain = null delChain+= a; delChain+=b; delChain (10,20);}

When (DelegateCaculate) Delegate.Combine (delChain, a), because there is only one an object in the delegate array, delChain simply points to a. The schematic diagram is as follows

When (DelegateCaculate) Delegate.Combine (delChain, b) is, because there are already two objects in the delegate array, a new MulticastDelegate object is generated for delChain to point to it, and _ invocationList points to a delegate array object, as shown below

If there is a delegate object to join, a new MulticastDelegate object will be generated again for delChain to point to the new object, and the original object will wait for the garbage collector to collect it. You can check the CLR source code. Each time you add a delegate object, the method NewMulticastDelegate is called, and the return value of this method is MulticastDelegate.

Delegation and interface

Both interfaces and delegates have the ability to call specific methods, so they are very similar in this respect. However, the interface requires that the type declaration of the target method must be compatible with the interface, and the delegate can be called by any type, as long as the target method signature of that type matches the delegate signature.

So when to use the delegate and when to use the interface? msdn summarized it very well, so I pasted it directly.

Delegates are useful in the following situations:

1. Call a single method.

2. A class wants to have multiple implementations of method specifications.

3. You want to allow static methods to implement the specification.

4. Want a design pattern for similar events.

5. The caller does not need to know or obtain the object that implements the method that matches the delegate signature.

6. The provider of the implementation wants to "distribute" the specification implementation to only a small number of selected components.

7. The combination of methods is needed.

Interfaces are useful in the following situations:

1. The specification defines a set of related methods.

2. Classes usually implement the specification only once.

3. The caller of the interface wants to convert to or from the interface type to get another interface or class.

The above is all the content of this article entitled "how to use reflection and delegation in C# method". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report