dynamic does not contain a definition for a property from a project reference

自作多情 提交于 2019-11-27 17:46:47

You need to use an ExpandoObject

 dynamic o = new ExpandoObject();
 o.Title = "Ghostbusters";
 o.Rating = "PG";

 Console.WriteLine(m.PrintMovie(o));
Robert Važan

Jahamal's answer doesn't say why you get the error. The reason is that the anonymous class is internal to the assembly. Keyword dynamic doesn't allow you to bypass member visibility.

The solution is to replace the anonymous class with named public class.

Here's another good example explaining the reason and another possible solution.

The reason the call to data2.Person fails is that the type information of data2 is not available at runtime. The reason it's not available is because anonymous types are not public. When the method is returning an instance of that anonymous type, it's returning a System.Object which references an instance of an anonymous type - a type who's info isn't available to the main program. The dynamic runtime tries to find a property called Person on the object, but can't resolve it from the type information it has. As such, it throws an exception. The call to data.Name works fine since Person is a public class, that information is available and can be easily resolved.

This can affect you in any of the following cases (if not more):

  1. You're returning a non-public, non-internal type using System.Object.
  2. You're returning a non-public, non-internal derived type via a public base type and accessing a property in the derived type that's not in the base type.
  3. You're returning anything wrapped inside an anonymous type from a different assembly.

In my case I had a Unit Test project that I created on Visual Studio and a lot of cases where I needed to test methods on a data layer library. I didn't want to change all of them so I marked the test assembly as a friend by using:

[assembly:InternalsVisibleTo("MyDataLayerAssemblyName")]

And that solved it.

Example:

using System.Runtime.CompilerServices;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[assembly: InternalsVisibleTo( "MyDataLayerAssembly" )]
namespace MyUnitTestProject.DataTests
{

   [TestClass]
   public class ContactTests
   {
      ...

References: InternalsVisibleToAttribute Class

Friend Assemblies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!