C # Use reflection to dynamically call class members

Source: Internet
Author: User

To use reflection to dynamically call class members, you need a method of the type class: invokemember. The statement for this method is as follows:

Public object invokemember (

String name,

Bindingflags invokeattr,

Binder binder,

Object target,

Object [] ARGs

);

Parameters

Name

String, which contains the name of the constructor, method, attribute, or field member to be called.

-Or-

An empty string ("") indicates the default Member of the call.

Invokeattr

One-bit blocking is composed of one or more bindingflags that specify the search execution method. Access can be one of bindingflags, such as public, nonpublic, Private, invokemethod, and getfield. You do not need to specify the search type. If the search type is omitted, bindingflags. Public | bindingflags. instance will be applied.

Binder

A binder object that defines a set of attributes and enables binding. Binding may involve selecting overload methods, mandatory parameter types, and calling members through reflection.

-Or-

If it is a null reference (nothing in Visual Basic), defaultbinder is used.

Target

The object on which the specified Member is to be called.

ARGs

An array containing parameters passed to the member to be called.

Return Value

Indicates the object returned by the called member.

Note:

The following bindingflags filter flag can be used to define members included in the search:

To obtain the returned value, bindingflags. instance or bindingflags. Static must be specified.

Specify bindingflags. Public to include public members in the search.

Specify bindingflags. nonpublic to include non-public members (Private Members and protected members) in the search ).

Specify bindingflags. flattenhierarchy to include static members in the hierarchy.

The following bindingflags modifier can be used to change the search execution method:

Bindingflags. ignorecase, indicating that the name case is ignored.

Bindingflags. declaredonly: searches for members declared on the type, rather than simply inherited members.

The following bindingflags call flag can be used to indicate the operations to be performed on members:

Createinstance, indicating to call the constructor. Ignore name. Invalid for other call flag.

Invokemethod indicates that a method is called, instead of a constructor or an initial value of the type. It is invalid for setfield or setproperty.

Getfield indicates obtaining the field value. It is invalid for setfield.

Setfield, indicating to set the field value. Invalid for getfield.

Getproperty indicates obtaining the property. It is invalid for setproperty.

Setproperty indicates setting properties. Invalid for getproperty.

CodeExample:

Class Program
{
Static void main (string [] ARGs)
{
Object OBJ;

Newsengine instance = (newsengine) system. reflection. Assembly. Load ("reflectiondata"). createinstance ("reflectiondata. newsengine ");

System. Diagnostics. Debug. writeline (instance. getitems ());

//
// Private string file = @ "dataaccess. dll ";

Reflectionengine r = new reflectionengine (@ "reflectiondata. dll ");
R. displaymodules ();
R. displaytypes ();
R. displaymethods ();
R. invokestaticmethod ();
R. invokemethod ();

Console. Read ();
}
}

Public class reflectionengine
{
Private string file;

Public reflectionengine (string file)
{
This. File = file;
}

// Display the names of all modules
Public void displaymodules ()
{
Console. writeline ("display modules ...");
Assembly = assembly. loadfrom (File );
Module [] modules = assembly. getmodules ();
Foreach (module in modules)
{
Console. writeline ("module name:" + module. Name );
}
}
// Display all types of names
Public void displaytypes ()
{
Console. writeline ("display types ...");
Assembly = assembly. loadfrom (File );
Type [] types = assembly. gettypes ();
Foreach (type in types)
{
Console. writeline ("type name:" + type. fullname );
}
}
// First, all method names in a type
Public void displaymethods ()
{
Console. writeline ("display methods in testreflection type ...");
Assembly = assembly. loadfrom (File );
Type type = assembly. GetType ("reflectiondata. newsengine ");
Methodinfo [] Methods = type. getmethods ();
Foreach (methodinfo method in methods)
{
Console. writeline ("method name:" + method. Name );
}
}
// Call the static method in a class
Public void invokestaticmethod ()
{
Console. writeline ("INVOKE static method ...");
Assembly = assembly. loadfrom (File );
Type type = assembly. GetType ("reflectiondata. newsengine ");

Type. invokemember ("getname", bindingflags. invokemethod, null, null, new object [] {});
}
// Call non-static methods in a class
Public void invokemethod ()
{
Console. writeline ("INVOKE method ...");
Assembly = assembly. loadfrom (File );
Type type = assembly. GetType ("reflectiondata. newsengine ");
Object OBJ = activator. createinstance (type );

Reflectiondata. newsengine Tc = (reflectiondata. newsengine) OBJ;

Console. writeline (type. invokemember ("getitems", bindingflags. invokemethod, null, TC, new object [] {});
Console. writeline (type. invokemember ("getitembyid", bindingflags. invokemethod, null, TC, new object [] {1 }));
}
}

========================================================== ========================================================== ====

Test code

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace reflectiondata
{

Public interface inewsengine
{
String name {Get ;}

String getitems ();

String getitembyid (int id );
}

Public class newsengine: inewsengine
{
Private string m_name = "common news engine ";

Public string name
{
Get {return m_name ;}
}

Public String getitems ()
{
Return "News's method-getitems ().";
}

Public String getitembyid (int id)
{
Return "News's method-getitembyid (" + ID + ").";
}

Public static string getname ()
{
Return "News's static method-getname ().";
}

}
}

Related Article

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.