使用'dynamic'抛出一个RuntimeBinderException [英] Use 'dynamic' throw a RuntimeBinderException

查看:167
本文介绍了使用'dynamic'抛出一个RuntimeBinderException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Peploe
{
    public string Name { get; set; }
}

public class Animal
{
    public string NickName { get; set; }
}

internal static class Program
{
    /// <summary>
    /// This 'ItemSorce' will be assignment by anywhere , so i don't know it have 'Name' property.
    /// </summary>
    public static IEnumerable ItemSource { get; set; }

    private static void Main()
    {
        var list = new List<Peploe>() {new Peploe() {Name = "Pato"}};
        ItemSource = list;

        //Test2
        //var animals = new List<Animal>() { new Animal() { NickName = "Pi" } };
        //ItemSource = animals;

        dynamic dy;
        foreach (var item in ItemSource)
        {
            dy = item;
            Console.WriteLine(dy.Name);//If I Uncomment 'Test2',it will throw a RuntimeBinderException at here.
        }
    }
}

可以解决这个问题。但是当'ItemSource'非常庞大时,'foreach'会多次执行,性能不好。我如何解决这个问题。

If I use reflection,it can resolve this problem. But when 'ItemSource' is very huge, the 'foreach' will excute many times,the performance is bad.How can I resolve this problem.

推荐答案

你需要添加一点反射,使得是完全动态的。并相信我,不会伤害性能,因为我已经使用它。这里是我从你的样本创建的代码示例。它仍然没有生产准备,但你会得到基本的想法如何你可以做到,与所有的限制。

You need to add little bit of reflection to make is complete dynamic. And trust me that will not hurt performance as I am already using it. Here is code sample I have created from you sample. It is still not production ready but you will get the basic idea how you can do it, with all your restriction.

dynamic dy;
            List<dynamic> result = new List<dynamic>(); 

            foreach (var item in ItemSource)
            {
                dy = new ExpandoObject();
                var d = dy as IDictionary<string, object>;

                foreach (var property in item.GetType().GetProperties())
                {
                    d.Add(property.Name, item.GetType().GetProperty(property.Name).GetValue(item, null));
                }

                result.Add(dy);
            }

            foreach (var item in result)
            {
                var r = ((dynamic)item) as IDictionary<string, object>;
                foreach (var k in r.Keys)
                {
                    Console.WriteLine(r[k] as string);
                }
            }

它不依赖于你在课堂上的任何属性。请让我知道是否需要任何进一步的细节。

This code works exactly way you want. Its not depended on whatever property you have in class. Please let me know if any further details needed.

这篇关于使用'dynamic'抛出一个RuntimeBinderException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆