Use reflection to dynamically call class members (generic)
Source: Internet
Author: User
1. generic class: Use invokeMethod in this class to dynamically call method in InvokeClass.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\
Public sealed class DynamicLoadMethod <T> where T: class
{
Private static object obj = new object ();
Private static T invokeMethod;
Public static T InvokeMethod
{
Get
{
Lock (obj)
{
If (invokeMethod = null)
{
InvokeMethod = typeof (T). InvokeMember (typeof (T). Name, BindingFlags. CreateInstance |
BindingFlags. Instance |
BindingFlags. NonPublic |
BindingFlags. Public, null) as T;
}
Return invokeMethod;
}
}
}
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\
2. dynamically called method Class
Public class InvokeClass
{
Private String Name;
Public String Names
{
Set {Name = value ;}
}
Public override string ToString ()
{
Return Name;
}
Private Object [] values = new Object [] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Public Object this [int index]
{
Get
{
Return values [index];
}
Set
{
Values [index] = value;
}
}
Public Object Value
{
Get
{
Return "the value ";
}
}
Public InvokeClass ()
{
Name = "initialName ";
}
Int methodCalled = 0;
Public void AddUp ()
{
MethodCalled ++;
Console. WriteLine ("AddUp Called {0} times", methodCalled );
}
Public void PrintTime ()
{
Console. WriteLine (DateTime. Now );
}
Public void Swap (ref int a, ref int B)
{
Int x =;
A = B;
B = x;
}
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\
3. Call Method
Static void Main (string [] args)
{
Console. WriteLine (DynamicLoadMethod <InvokeClass>. InvokeMethod. Value as String );
DynamicLoadMethod <InvokeClass>. InvokeMethod. AddUp ();
DynamicLoadMethod <InvokeClass>. InvokeMethod. Names = "BrianLei Build ";
Console. WriteLine (DynamicLoadMethod <InvokeClass>. InvokeMethod. ToString ());
} Finally, I tested the Loop100 million times,
It takes only 20 milliseconds to call the method directly,
It took 12 seconds to call the method dynamically.
So everyone knows how this idea works.
It is best not to use web form.
We can try it in win form.
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