返回/消耗跨越组件边界动态匿名类型边界、组件、消耗、类型

2023-09-02 01:33:16 作者:愛情~睡醒了、

在code以下的伟大工程。如果获取使用方法是在不同的组件中,code失败,出现RuntimeBinderException。这是因为.NET运行时系统只能保证匿名类型的共性(<字符串,INT> 在这种情况下)组件内。

有没有骗过运行时系统来克服这个办法吗?我可以检查对象上的使用边调试器,调试器可以看到相关属性。

 类节目
{
    静态无效的主要(字串[] args)
    {
        UsePerson();
        到Console.ReadLine();
    }

    公共静态无效UsePerson()
    {
        变种人= GetPerson();

        Console.WriteLine(person.Name);
    }

    公共静态动态GetPerson()
    {
        返回新{名称=富,年龄= 30};
    }
}
 

解决方案

使用的 ExpandoObject 而不是匿名类型。这应该让你跨越程序集边界安全:

 公共静态动态GetPerson()
{
    动态的人=新ExpandoObject();
    person.Name =富;
    person.Age = 30;

    返回的人;
}
 
现在还有啥境外消费返刷卡金之类的活动么

在一般情况下,匿名类型应该真正仅在产生它们的方法相同的方法中使用。从方法返回匿名类型,则在一般情况下,将要造成更多的问题比它解决

The code below works great. If the Get and Use methods are in different assemblies, the code fails with a RuntimeBinderException. This is because the .Net runtime system only guarantees commonality of anonymous types (<string, int> in this case) within assemblies.

Is there any way to fool the runtime system to overcome this? I can inspect the object in the debugger on the Use side, and the debugger can see the relevant properties.

class Program
{
    static void Main(string[] args)
    {
        UsePerson();
        Console.ReadLine();
    }

    public static void UsePerson()
    {
        var person = GetPerson();

        Console.WriteLine(person.Name);
    }

    public static dynamic GetPerson()
    {
        return new { Name = "Foo", Age = 30 };
    }
}

解决方案

Use an ExpandoObject instead of an anonymous type. This should allow you to cross assembly boundaries safely:

public static dynamic GetPerson()
{
    dynamic person = new ExpandoObject();
    person.Name = "Foo";
    person.Age = 30;

    return person;
}

In general, anonymous types should really only be used within the same method in which they are generated. Returning an anonymous type from a method is, in general, going to cause more problems than it solves.