Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

c# - 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'.

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);

What do I need to do to make anonymous types work across dlls as dynamic types - or is that not possible?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")]

but there are drawbacks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...