How to call a method through reflection?

Source: Internet
Author: User
Tags mathematical functions
How to call a method?

This example illustrates how to call various methods through reflection. Because the name of the called method is stored in a string, this mechanism provides the function to specify the method to be called at runtime (rather than during design, it provides a space for your users to control which specific method to call. Although this demonstration focuses on calling methods, you can set and obtain attributes and fields as needed. For another example of how to teach in this topic, see examples under the topic of how to use mathematical functions.

 

C # ListMembers. aspx

[Running example] | [View Source Code]

In many code schemes, you know the task to be implemented before executing the task. Therefore, you can specify the methods to be called and the parameters to be passed to them. However, in some cases, you may want to dynamically call a method based on a specific scheme or user operation. This feature is available throughReflectionNamespace usage by usingTypeObjectInvokeMemberMethod.

You can also perform other operations, such as obtaining or setting the value of a specified attribute. These operations can be performed throughBindingFlagsEnumeration.InvokeMethodThe second parameter you specifyBindingFlagsA combination of operations. For example, if you want to call a static method on a class, you canBindingFlagsAndInvokeMethod BindingFlagIncluding the static element. The following example shows how to call a hypothetical method named SayHello, where SayHello is a static method.


// calling a static method, receiving no arguments// don't forget that we are using object in the reflection namespace...using System;using System.Reflection;public class Invoke {public static void Main (String [] cmdargs) {// Declare a type object, used to call our InvokeMember method...Type t = typeof (TestClass);// BindingFlags has three bitor'ed elements. Default indicates// that default binding rules should be applied.t.InvokeMember ("SayHello",BindingFlags.Default | BindingFlags.InvokeMethod| BindingFlags.Static, null,null, new object [] {});}}
'  calling a static method, receiving no arguments'  don't forget that we are using object in the reflection namespace...Imports SystemImports System.ReflectionPublic Class InvokePublic Shared Sub Main ()'  Declare a type object, used to call our InvokeMember method...Dim t As Type = GetType (TestClass)'  BindingFlags has three bitor'ed elements. Default indicates that'  default binding rules should be applied.t.InvokeMember ("SayHello", _BindingFlags.Default BitOr BindingFlags.InvokeMethod _BitOr BindingFlags.Static, nothing, _nothing, new object () {})End SubEnd Class
C # VB  

Quickly view the information passedInvokeOther parameters of the method. The first null parameter request passed uses the default concatenation program to bind the method being called. When calling the default concatenation program, include the defaultBindingFlags. The third parameter can be left blank. You can specifyBinderObject, which defines a set of properties and enables binding. This may involve selecting an overloaded method or a forced parameter type. The second null parameter is the object on which you call the selected method. Finally, an array of parameter objects received by members is passed. In this example, the SayHello method does not receive any parameters, so an empty array is passed.

The following situations are slightly different. Call another static method named ComputeSum, but in this case, this method requires two parameters. Therefore, fill in an object array with these parameters and pass them as the last parameterInvokeMember.

// Calling a static method, which needs argumentsobject [] args = new object [] {100.09, 184.45};// we know that this particular method returns a value, being the computed sum,// so we create a variable to hold the return// note the datatype of the return is object, the only datatype InvokeMethod returns...object result;// invoke the method. Note the change in the last parameter: the array we populated...result = t.InvokeMember ("ComputeSum", BindingFlags.Default | _BindingFlags.InvokeMethod | BindingFlags.Static,null, null, args);// write the results to the user's console...Console.WriteLine ("{0} + {1} = {2}", args[0], args[1], result);
'  Calling a static method, which needs argumentsDim args as object ()args = new object () {100.09, 184.45}'  we know that this particular method returns a value, being the computed sum,'  so we create a variable to hold the return'  note the datatype of the return is object, the only datatype InvokeMethod returns...Dim result As object'  invoke the method. Note the change in the last parameter: the array we populated...result = t.InvokeMember ("ComputeSum", BindingFlags.Default BitOr _BindingFlags.InvokeMethod BitOr BindingFlags.Static, _nothing, nothing, args)'  write the results to the user's console...Console.WriteLine ("{0} + {1} = {2}", args(0), args(1), result)
C # VB  

In the first two examples, the static method has been called. You can also call the instance method. To do this, pass the object of the type on which you want to call the method as the third parameter. This example also showsInvokeMember, You do not have to have actualTypeObject. In this case, you usually want to use the class instance to call GetType, as shown in the following example. Note that because no static method is calledBindingFlagsChanged.

// Calling  an instance method// we need an object reference to invoke an instance memberTestClass c = new TestClass ();// use the instance of our class to call GetType// we no longer include the Static element in BindingFlags for our |// the fourth parameter is no longer null: we instead pass an instance// of the object we wish to invoke our method onc.GetType().InvokeMember ("AddUp", BindingFlags.Default | BindingFlags.InvokeMethod,null, c, new object [] {});c.GetType().InvokeMember ("AddUp", BindingFlags.Default | BindingFlags.InvokeMethod,null, c, new object [] {});
'  Calling  an instance method'  we need an object reference to invoke an instance memberDim c as TestClassc = new TestClass ()'  use the instance of our class to call GetType'  we no longer include the Static element in BindingFlags for our bitor'  the fourth parameter is no longer null: we instead pass an instance'  of the object we wish to invoke our method onc.GetType().InvokeMember ("AddUp", BindingFlags.Default BitOr BindingFlags.InvokeMethod, _nothing, c, new object () {})c.GetType().InvokeMember ("AddUp", BindingFlags.Default BitOr BindingFlags.InvokeMethod, _nothing, c, new object () {})
C # VB  

Sometimes you do not want to call a method, but you need to call other Members, such as attributes or fields. To implement it, you only need to changeBindingFlagsCombination (insteadInvokeMethod) To include the appropriate elements. The following example shows how to obtain and set field values. The discussed field is not a static field, so you need to create an object instance to request this field. When setting the field value, you must pass the set value as the unique element of the object array parameter. When getting the value, you needInvokeMemberThe return type of the method is assigned to an object.

// Setting a field. Assume we are using the same Type and Class declared in the// previous examples (t and c). The field we are setting is the Name field// note the BindingFlags argument now includes SetField rather thanInvokeMember// Further, this is an instance field, so we pass the instance of our classt.InvokeMember ("Name", BindingFlags.Default | BindingFlags.SetField,null, c, new object [] {"NewName"});// similar usage...result = t.InvokeMember ("Name", BindingFlags.Default | BindingFlags.GetField,null, c, new object [] {});Console.WriteLine ("Name == {0}", result);
'  Setting a field. Assume we are using the same Type and Class declared in the'  previous examples (t and c). The field we are setting is the Name field'  note the BindingFlags argument now includes SetField rather thanInvokeMember'  Further, this is an instance field, so we pass the instance of our classt.InvokeMember ("Name", BindingFlags.Default BitOr BindingFlags.SetField, _nothing, c, new object () {"NewName"})'  similar usage...result = t.InvokeMember ("Name", BindingFlags.Default BitOr BindingFlags.GetField, _nothing, c, new object () {})Console.WriteLine ("Name == {0}", result)
C # VB  

You can also obtain and set attributes, but in this example, it is assumed that the set attribute is an array or set with multiple elements. To specify the settings of a specific element, you must specify the index. To set attributes, BindingFlags. SetProperty is assigned. To specify a SET index or an array index for an attribute, place the index value of the element in the first element of the object array, and then set the value as the second element. To retrieve this attribute, pass the index as a unique element in the object array and specify BindingFlags. GetProperty.

// Set an indexed property valueint index = 3;// specify BindingFlags.SetProperty, and because this is an instance property,// pass the object to call the property on (c). In the object array, make two elements,// the first being the index, and the second being the value to sett.InvokeMember ("Item", BindingFlags.Default |BindingFlags.SetProperty,null, c, new object [] {index, "NewValue"});// Get an indexed property value// specify BindingFlags.GetProperty, and because this is an instance property,// pass the object to call the property on (c). In the object array, specify the index onlyresult = t.InvokeMember ("Item", BindingFlags.Default |BindingFlags.GetProperty,null, c, new object [] {index});Console.WriteLine ("Item[{0}] == {1}", index, result);
' Set an indexed property valueDim  index As Int32 = 3'  specify BindingFlags.SetProperty, and because this is an instance property,'  pass the object to call the property on (c). In the object array, make two elements,'  the first being the index, and the second being the value to sett.InvokeMember ("Item", BindingFlags.Default BitOr BindingFlags.SetProperty, _nothing, c, new object () {index, "NewValue"})'  Get an indexed property value'  specify BindingFlags.GetProperty, and because this is an instance property,'  pass the object to call the property on (c). In the object array, specify the index onlyresult = t.InvokeMember ("Item", BindingFlags.Default BitOr BindingFlags.GetProperty, _nothing, c, new object () {index})Console.WriteLine ("Item[{0}] == {1}", index, result)
C # VB  

You can also use named parameters, in which case you need to useInvokeMemberMethod. Create an array of object parameters as it has been so far, and create a string array of the name of the passed parameter. The overload method you want to use accepts the parameter name list as the last parameter, and accepts the list of values to be set as the fifth parameter. In this demonstration, all other parameters can be null (except the first two ).

// Calling a method using named arguments// the argument array, and the parameter name array. Obviously, you will need// to determine the names of the parameters in advanceobject[] argValues = new object [] {"Mouse", "Micky"};String [] argNames = new String [] {"lastName", "firstName"};// the first five parameters for this overloaded method are the same as the// the five parameters we have used to this point. The final parameter needs to be// set to the names of the parameterst.InvokeMember ("PrintName", BindingFlags.Default | BindingFlags.InvokeMethod,null, null, argValues, null, null, argNames);
'  Calling a method using named arguments'  the argument array, and the parameter name array. Obviously, you will need'  to determine the names of the parameters in advanceobject[] argValues = new object [] {"Mouse", "Micky"};String [] argNames = new String [] {"lastName", "firstName"};'  the first five parameters for this overloaded method are the same as the'  the five parameters we have used to this point. The final parameter needs to be'  set to the names of the parameterst.InvokeMember ("PrintName", BindingFlags.Default BitOr BindingFlags.InvokeMethod, _nothing, nothing, argValues, nothing, nothing, argNames)
C # VB  

The next example shows how to call the default members of a class. Make sure that the class on which the call is made has a default member. ThenInvokeMemberDo not specify the name of the member to be called, as shown in this example.

// our class with it's default member specified, using the defaultmemeber attribute[DefaultMemberAttribute ("PrintTime")]public class TestClass2 {public void PrintTime () {Console.WriteLine (DateTime.Now);}}// the client code that uses the above class...Type t3 = typeof (TestClass2);t3.InvokeMember ("", BindingFlags.Default |BindingFlags.InvokeMethod,null, new TestClass2(), new object [] {});
'  our class with it's default member specified, using the defaultmemeber attributepublic  class 
      TestClass2public Sub PrintTime ()Console.WriteLine (DateTime.Now)End SubEnd Class'  the client code that uses the above class...Dim t3 As Typet3 = GetType (TestClass2)t3.InvokeMember ("", BindingFlags.Default  BitOr BindingFlags.InvokeMethod, _nothing, new TestClass2(), new object () {})
C # VB  

The last example uses a slightly different procedure call method. Not directly usedTypeObject, but directly create a separateMethodInfoObject To indicate the method to be called. Then callMethodInfoObjectInvokeMethod to pass the instance of the object on which the method needs to be called (if you want to call the instance method, but if the method is static, It is null ). An array of objects that require parameters, as before. If necessary, this example allows you to pass parameters by referencing.

// Invoking a ByRef memberMethodInfo m = t.GetMethod("Swap");args = new object[2];args[0] = 1;args[1] = 2;m.Invoke(new TestClass(),args);Console.WriteLine ("{0}, {1}", args[0], args[1]);
'  Invoking a ByRef memberDim m as MethodInfo =m = t.GetMethod("Swap")args = new object() {CObj(1), CObj(2)}m.Invoke(new TestClass(),args)Console.WriteLine ("{0}, {1}", args(0), args(1))
C # VB  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.