我收到一条错误消息:
'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}
这是一个屏幕截图:
我正在做这样的事情并尝试从测试项目中调用电影功能。
最佳答案
Jahamal 的回答没有说明为什么您会收到错误。原因是匿名类是程序集的内部
。关键字 dynamic
不允许您绕过成员可见性。
解决方案是将匿名类替换为命名公共(public)类。
这是解释原因的另一个很好的例子 another possible solution .
The reason the call to
data2.Person
fails is that the type information ofdata2
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 aSystem.Objec
t 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 calledPerson
on the object, but can't resolve it from the type information it has. As such, it throws an exception. The call todata.Name
works fine sincePerson
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):
- 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/