Improved reflection using dynamic types

Source: Internet
Author: User

First, declare the Application Scenario:

1. If the function name is determined during compilation and the object type is determined during runtime, it is a good idea to use dynamic.
2. If the function name is determined during compilation and the object type is also determined during compilation, no reflection or dynamic is required.
3. If the function name can be determined at runtime, the function name is a string and must be completed using reflection.

 

So we must use the dynamic type improvement reflection in the first case: (the function name is determined during compilation and the object type is determined during runtime)

Assume that the function to be called by reflection is:

ClassLibrary
{
Demo
{
GetName ()
{
Name = "dddd ";
Name;
}
}
}

Traditional calls are generally:

Main ([] args)
{
Typeinfo =. Load ("ClassLibrary"). GetType ("ClassLibrary. Demo ");
Instance =. Load ("ClassLibrary"). CreateInstance ("ClassLibrary. Demo ");
Me = typeinfo. GetMethod ("GetName ");
Ret = me. Invoke (instance ,);
. WriteLine (ret. ToString ());

}

After improvement:

Program
{
ReflectObj =;

([] Args)
{
If (reflectObj =)
{
ReflectObj =. Load ("ClassLibrary"). CreateInstance ("ClassLibrary. Demo ");
}
Rrr = reflectObj. GetName ();

. WriteLine (rrr. ToString ());

. ReadKey ();
}
}

 

The step of reflecting the production function is missing, which is also very helpful for the reflection Performance Tuning later on :)

 

 

 

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.