LINQ to reflection (reflection)

Source: Internet
Author: User
Introduction

We often use reflection, which is inevitable during development. However, there is no suitable class library to help us make better use of reflection. From the early fastinvoker to the fastreflectionlib of Lao Zhao, all of them emphasize fast. This is because the performance loss of reflection is very high, so everyone is focused on solving performance problems, but there are few improvements in ease of use. Today, I bring you a reflection class library that combines both performance and good user experience.

. Metadata ()

This type of library is based on LINQ to object. You can call the. Metadata () method to obtain the complete metadata information of the corresponding type. This information will be cached and the core Lambda of fastreflectionlib will be usedCodeIn place of direct reflection.

 
Public StaticMetadata metadata (This ObjectInstance)
{
ReturnMetadatacache. Create (instance );
}

First define a mockobject

         Class Mockattribute: attribute
{
Public Mockattribute ( String Name)
{
This . Name = Name;
}
Public String Name
{
Get; set;
}
}

Class Mockobject
{
Public String Country = "China" ;

[Mock ( "This is the name" )]
Public String Name
{
Get; set;
}
Public String Blog
{
Get; set;
}
[Mock ( "This is the location" )]
Public String Location
{
Get; set;
}
Public String Sayhello ( String Name)
{
Return "Hi ," + Name;
}
}
}

 

1. How do I obtain an attribute and assign values?

UsingSparrow. reflection;
[Testmethod]
Public VoidSet_property_value ()
{
VaR OBJ =NewMockobject {name ="DayI", Blog =Http://walkingboy.cnblogs.com", Location ="Xiamen"};
VaR property = obj. Metadata (). properties. Where (I => I. Name ="Location"). Firstordefault ();
VaR changedlocation ="Xiamen, China";
// Get value// VaR value = property. getvalue (OBJ );Property. setvalue (OBJ, changedlocation); Assert. areequal (changedlocation, obj. Location );}

2. If you get the value of a field?

UsingSparrow. reflection;
[Testmethod]
Public VoidGet_field_value ()
{
VaR OBJ =NewMockobject ();

VaR field = obj. Metadata (). Fields. Where (I => I. Name ="Country"). Firstordefault ();

Assert. areequal ("China", Field. getvalue (OBJ ));
}

3. How to obtain a custom matmattribute?

UsingSparrow. reflection;
[Testmethod]
Public VoidGet_custom_attribute_data ()
{
VaR OBJ =NewMockobject {name ="DayI", Blog =Http://walkingboy.cnblogs.com", Location ="Xiamen"};


VaR attribute = obj. Metadata (). Properties
. Where (I => I. Name ="Name")
. Selecttes (I => I. attributes)
. Select (I => I. Attribute)
. Oftype <mockattribute> ()
. Firstordefault ();

Assert. areequal ("This is the name", Attribute. Name );
}

4. How to call a method with a specified name?

UsingSparrow. reflection;
[Testmethod]
Public VoidInvoke_method ()
{
VaR OBJ =NewMockobject ();

VaR method = obj. Metadata (). Methods. Where (I => I. Name ="Sayhello"). Firstordefault ();

Assert. areequal ("Hi, World", Method. Invoke (OBJ,New[] {"World"}));
}
. Proxy ()

In some application scenarios, you may need to write a lot of code to query and obtain a single method, attribute, and field using LINQ to object. First. Metadata (), then. Where (), although the Code is elegant, there is still a lot of work to do. Therefore, here we also provide an alternative way to obtain a single method, attribute, and field.

Public StaticProxy proxy (This ObjectInstance)
{
Return NewProxy (instance );
}

1. How to obtain the value of an attribute

 
UsingSparrow. reflection;
[Testmethod]
Public VoidGet_value_via_property_proxy ()
{
VaR OBJ =NewMockobject {name ="DayI", Blog =Http://walkingboy.cnblogs.com", Location ="Xiamen"};

Assert. areequal (obj. Name, obj. Proxy (). properties ["Name"]);
}

 

2. How to set a property value

UsingSparrow. reflection;
[Testmethod]
Public VoidSet_value_via_property_proxy ()
{
VaR OBJ =NewMockobject {name ="DayI", Blog =Http://walkingboy.cnblogs.com", Location ="Xiamen"};

VaR changedlocation ="Xiamen, China";
OBJ. Proxy (). properties ["Location"] = Changedlocation;

Assert. areequal (changedlocation, obj. Location );
}

3. How to obtain the value of a field

UsingSparrow. reflection;
[Testmethod]
Public VoidGet_value_via_field_proxy ()
{
VaR OBJ =NewMockobject {name ="DayI", Blog =Http://walkingboy.cnblogs.com", Location ="Xiamen"};

Assert. areequal (obj. Country, obj. Proxy (). Fields ["Country"]);
}

 

4. How to call a method

UsingSparrow. reflection;
[Testmethod]
Public VoidInvoke_method_via_method_proxy ()
{
VaR OBJ =NewMockobject ();

Assert. areequal ("Hi, World", Obj. Proxy (). Methods ["Sayhello"] (New[] {"World"}));
}
. Proxy () vs dynamic

We know that the keyword dynamic is introduced in C #4, making duck typing (dynamicduck: Duck typing in a dynamic world) a possibility. View the following code:

 
Public VoidRun (Dynamic OBJ)
{
Console. writeline (obj. Name );
}

 

This Code does not specify the object type. The object type is determined by the actual value passed in during the runtime, as long as the type contains a name attribute.

But is it enough to support duck typing? Not dynamic enough. Here. the name is determined at the time of compilation (or encoding). However, in our use scenarios, this is dynamic, for example, self-form or configuration information, dynamic is powerless at this time.

In turn, let's look at the use of. Proxy ().

 
Public VoidRun (ObjectOBJ,StringPropertyname)
{
Console. writeline (obj. Proxy (). properties [propertyname])
}

 

 

It not only supports duck typing, but also supports dynamic attribute names. Is there a script (JavaScript ...) How does it feel?

Code download http://sparrow.codeplex.com/releases/view/50364

Detailed document http://sparrow.codeplex.com/wikipage? Title = LINQ-to-Reflection

 

This article is based on the signature 2.5 mainland China License Agreement, genuine licensed, if there are similar, all are shanzhai, the author reserves the right to pursue, in the case of retaining the signature of this article Chen dayI (including links, reprinted, interpreted, or used for commercial purposes. If you have any questions or negotiate with the Authority, please contact me via e-mail/MSN.

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.