c# - 动态不包含项目引用中属性的定义

标签 c# .net dynamic dynamicobject

我收到一条错误消息:

'object' does not contain a definition for 'Title'

所有代码也在github

我有一个看起来像这样的 ConsoleApplication1

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Movie m = new Movie();
            var o = new { Title = "Ghostbusters", Rating = "PG" };
            Console.WriteLine(m.PrintMovie(o));
        }
    }
} 

Movie.cs

public class Movie : DynamicObject
{
    public string PrintMovie(dynamic o)
    {
        return string.Format("Title={0} Rating={1}", o.Title, o.Rating);
    }
} 

它在同一个项目中运行良好,但如果我添加 ConsoleApplication2 并引用 ConsoleApplication1 并添加完全相同的代码

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Movie m = new Movie();
            var o = new { Title = "Ghostbusters", Rating = "PG" };
            Console.WriteLine(m.PrintMovie(o));
        }
    }
}

我得到一个错误:

'object' does not contain a definition for 'Title'**

即使它在动态对象中。

  • o.Title 'o.Title' 引发了类型为 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' 的异常动态 {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException}

这是一个屏幕截图:enter image description here

我正在做这样的事情并尝试从测试项目中调用电影功能。

最佳答案

Jahamal 的回答没有说​​明为什么您会收到错误。原因是匿名类是程序集的内部。关键字 dynamic 不允许您绕过成员可见性。

解决方案是将匿名类替换为命名公共(public)类。

这是解释原因的另一个很好的例子 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 whose 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.

关于c# - 动态不包含项目引用中属性的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9416095/

相关文章:

c# - .net 随机生成器是如何实现的?

Java 更改托盘图标

javascript - 使用动态名称在 ES6 中创建类的实例?

c# - IndexOf() 有反义词吗?也许 NotIndexOf()?

c# - 使用 ContentPresenter 和 ItemsPresenter 的自定义控件

c# - Linq Select 方法,一个方法作为一个参数,有两个参数

c# - c#连接mysql执行存储过程报错 "Data too long for column"

c# - 如何在 JetBrains Rider 中添加/使用 C# 库?

c# - 使用反射来获取对象属性的属性

c# - 检测代码中的动态类型?