C#“动态"无法访问在另一个程序集中声明的匿名类型的属性 [英] C# ‘dynamic’ cannot access properties from anonymous types declared in another assembly
问题描述
下面的代码运行良好,只要我在与 Program
类相同的程序集中有 ClassSameAssembly
类.但是当我将 ClassSameAssembly
类移动到一个单独的程序集时,会抛出一个 RuntimeBinderException
(见下文).有没有可能解决它?
Code below is working well as long as I have class ClassSameAssembly
in same assembly as class Program
.
But when I move class ClassSameAssembly
to a separate assembly, a RuntimeBinderException
(see below) is thrown.
Is it possible to resolve it?
using System;
namespace ConsoleApplication2
{
public static class ClassSameAssembly
{
public static dynamic GetValues()
{
return new
{
Name = "Michael", Age = 20
};
}
}
internal class Program
{
private static void Main(string[] args)
{
var d = ClassSameAssembly.GetValues();
Console.WriteLine("{0} is {1} years old", d.Name, d.Age);
}
}
}
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
:对象"不包含名称"的定义
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at ConsoleApplication2.Program.Main(String[] args) in C: empProjectsConsoleApplication2ConsoleApplication2Program.cs:line 23
推荐答案
我相信问题在于匿名类型是作为 internal
生成的,所以绑定器并不真正知道"它
I believe the problem is that the anonymous type is generated as internal
, so the binder doesn't really "know" about it as such.
尝试改用 ExpandoObject:
Try using ExpandoObject instead:
public static dynamic GetValues()
{
dynamic expando = new ExpandoObject();
expando.Name = "Michael";
expando.Age = 20;
return expando;
}
我知道这有点难看,但这是我目前能想到的最好的......我认为你甚至不能使用对象初始值设定项,因为虽然它被强类型化为 ExpandoObject代码> 编译器不知道如何处理姓名"和年龄".你可能可以这样做:
I know that's somewhat ugly, but it's the best I can think of at the moment... I don't think you can even use an object initializer with it, because while it's strongly typed as ExpandoObject
the compiler won't know what to do with "Name" and "Age". You may be able to do this:
dynamic expando = new ExpandoObject()
{
{ "Name", "Michael" },
{ "Age", 20 }
};
return expando;
但这也好不到哪里去...
but that's not much better...
您可以潜在地编写一个扩展方法,通过反射将匿名类型转换为具有相同内容的 expando.然后你可以写:
You could potentially write an extension method to convert an anonymous type to an expando with the same contents via reflection. Then you could write:
return new { Name = "Michael", Age = 20 }.ToExpando();
虽然这很可怕:(
这篇关于C#“动态"无法访问在另一个程序集中声明的匿名类型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!