A pitfall of dynamic -- runtimebinderexception: "object" does not contain the definition of "XXX"

Source: Internet
Author: User

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"

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.