[英]Accessing properties of anonymous/dynamic types across dll boundaries gives RuntimeBinderException
In the following sample, x.propertyX works fine, whereas y.propertyX gives me a Microsoft.CSharp.RuntimeBinder.RuntimeBinderException , complaining 'propertyX' is not defined in 'object'.在下面的示例中, x.propertyX工作正常,而y.propertyX给了我一个Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ,抱怨“object”中没有定义“propertyX”。
The CreateDynamic method in the Program class (shown below) and the one in Class1 (not shown) are exactly the same, but Class1 is in a different project from Program. Program 类中的 CreateDynamic 方法(如下所示)和 Class1 中的 CreateDynamic 方法(未显示)完全相同,但 Class1 与 Program 在不同的项目中。 If I move Class1 into Program's project, everything works fine.
如果我将 Class1 移到 Program 的项目中,则一切正常。
class Program
{
public static object CreateDynamic()
{
return new { propertyX = "asdf" };
}
static void Main(string[] args)
{
dynamic x = CreateDynamic();
Console.WriteLine(x.propertyX);
dynamic y = Class1.CreateDynamic();
Console.WriteLine(y.propertyX);
What do I need to do to make anonymous types work across dlls as dynamic types - or is that not possible?我需要做什么才能使匿名类型作为动态类型跨 dll 工作 - 或者这是不可能的?
Update: Fwiw, I figured out that I can get around that using ExpandoObjects, which I then 'cast' to dynamic, but ExpandoObjects are are not as nicely instantiable, when compared to the更新: Fwiw,我发现我可以使用 ExpandoObjects 解决这个问题,然后我将其“转换”为动态,但与
new { key1 = val1, key2 = val2 }
style that anonymous types offer.匿名类型提供的样式。
Anonymous types are internal to the assembly they are created in. If you have control over the source code you can make them Friend Assemblies匿名类型是创建它们的程序集内部的。如果您可以控制源代码,您可以将它们设为Friend 程序集
[assembly:InternalsVisibleTo("TheOtherAssembly")]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.