Today, when I read "LINQ in action", I suddenly came up with the idea of using expression and LINQ to quickly access object attributes. If we put an object in an array for query, and then use select to project the required attributes, we can achieve quick access. Although it is much slower than direct access, it is still very good that it is faster than the reflection method by an order of magnitude. Assume that an object class is defined as follows: public class user
...{
Public string name
... {Get; set ;}
Public int age
... {Get; set ;}
} If we want to access the value of the Name field, VAR books = new user []... {new user... {name = "Lucifer", age = 26 }};
Var val = books. select (Book => book. name ). first (); it's very simple, right? Next, you just need to translate it with expression and compile it into a generic one. The Code is as follows: using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. LINQ. expressions;
Using system. diagnostics;
Public class quickaccess <t>
...{
Static dictionary <int, delegate> _ pmap = new dictionary <int, delegate> ();
Static T [] _ lst = new T []... {default (t )};
Public static P get_properyval <p> (t obj, string pname)
...{
VaR func = default (func <T, P> );
_ Lst [0] = OBJ;
Return enumerable. Select (_ lst, func). First ();
}
}
// Call the code
Int val = 0;
VaR user = new user... {name = "Lucifer", age = 26 };
Stopwatch SW1 = new stopwatch ();
Sw1.start ();
For (INT I = 0; I <10000000; ++ I)
...{
Val = quickaccess <user>. get_properyval <int> (user, "Age ");
}
Sw1.stop ();
Console. writeline (sw1.elapsedmilliseconds.
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.