C #4.0 cross-Assembly use of "dynamic"

Source: Internet
Author: User

When writing code today, I was lazy and used dynamic. As a result, I encountered a problem and I was unable to get the attributes of the dynamic object at runtime. The original problem is simplified as follows:

Assembly A contains the SampleClass class. There is A static method that receives A dynamic type parameter and outputs its Value attribute.

Public classSampleClass {public static void Output (dynamic result) {Console. WriteLine (result. Value );}}

Assembly B References Assembly A and calls the Output method:

SampleClass. Output (new {Value = something. CurrentValue });

The running result is:

"Unhandled Exception: Microsoft. CSharp. RuntimeBinder. RuntimeBinderException: object does not contain a definition for Value"

In addition, the Value Attribute Value of result can be seen during debugging:

We can also use reflection to see that the attribute Value exists, but here the output is not possible. Why?

 

 

------------------------------------------

A: Because the anonymous type is private by default, the anonymous type defined in the B program set cannot be directly obtained from Assembly A, and thus cannot be output. The solution is to pre-define the public data type. Therefore, there are still many restrictions on the use of the anonymous type, and similar problems also occur in the anonymous method.

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.