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.