Create a console program and a class library, create an anonymous object on the console, and then access it in the class library. The Code is as follows:
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { var obj = new { Id = 1 }; var c = new ClassLibrary1.TestClass(); c.Test(obj); Console.ReadLine(); } }}
namespace ClassLibrary1{ public class TestClass { public void Test(dynamic obj) { Console.WriteLine(obj.Id); } }}
Compilation is normal, but a prompt is displayed at runtime.
"Microsoft. CSHARP. runtimebinder. runtimebinderexception" type unprocessed exception occurs in system. Core. dll
Other information: "object" does not contain the definition of "ID"
The ID attribute must exist. What is the problem?
Let's use ildasm to view the program and we will find that the declared anonymous type is at the internal level.
Internal can only be accessed in the same set of programs. At runtime, dynamic will naturally report an error if it wants to find the internal type attribute in another assembly.
After knowing the cause, it is easy to solve the problem. You only need to add it to assemblyinfo. CS of the current Assembly.
[assembly: InternalsVisibleTo("ClassLibrary1")]
Specify to be visible to the specified assembly.
A pitfall of dynamic -- runtimebinderexception: "object" does not contain the definition of "XXX"