跨DLL边界访问匿名/动态类型的属性会给出RuntimeBinderException [英] Accessing properties of anonymous/dynamic types across dll boundaries gives RuntimeBinderException
问题描述
在以下示例中, x.propertyX 可以正常工作,而 y.propertyX 给我一个 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ,抱怨"propertyX"未在对象"中定义.
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'.
Program类中的CreateDynamic方法(如下所示)与Class1中的CreateDynamic方法(未显示)完全相同,但是Class1与Program在不同的项目中.如果我将Class1移到Program的项目中,一切正常.
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. If I move Class1 into Program's project, everything works fine.
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);
我该怎么做才能使匿名类型跨dll作为动态类型工作-还是不可能?
What do I need to do to make anonymous types work across dlls as dynamic types - or is that not possible?
更新:首先,我发现可以使用ExpandoObjects解决该问题,然后将其转换"为动态,但是与之相比,ExpandoObjects的实例化效果不佳>
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
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
[assembly:InternalsVisibleTo("TheOtherAssembly")]
,但是有缺点.
这篇关于跨DLL边界访问匿名/动态类型的属性会给出RuntimeBinderException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!