Use dynamic to simplify reflection implementation

Source: Internet
Author: User

Dynamic is a new feature of Framework4.0. The emergence of dynamic makes C # have the characteristics of a weak language type. during compilation, the compiler does not check the type and reports no error, however, if a non-existent attribute or method is executed during running, the running program throws a RuntimeBinderException. The difference between var and dynamic var is the syntactic sugar provided by the compiler. The actual type will be matched during compilation and the declaration of replacing the variable. After a dynamic is compiled, it is actually an object type, except that the compiler performs special processing on dynamic and places the type check during runtime. From the compiler window of VS, we can see that the variables declared by var have smart prompts in VS, because VS can infer the actual type, and the variables declared by dynamic have no smart prompts. Use dynamic to simplify reflection and copy the code public class DynamicSample {public string Name {get; set;} public int Add (int a, int B) {return a + B ;}} public partial class DynamicPage: System. web. UI. page {protected void Page_Load (object sender, EventArgs e) {// common reflection practices DynamicSample dynamicSample = new DynamicSample (); var addMethod = typeof (DynamicSample ). getMethod ("Add"); int res = (int) addMethod. invoke (dynamicSa Mple, new object [] {1, 2}); // dynamic method, concise, recommended dynamic dynamicSample2 = new DynamicSample (); int res2 = dynamicSample2.Add (1, 2 ); // Add will not be intelligently prompted} another advantage of using dynamic to copy code is that it has better reflection performance than it has not been optimized. It is equivalent to the optimized reflection performance, but the code is clean and tidy, the author has also pasted the code and posted the running results. I have not introduced them much, so I will do it here.

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.