如何调用动态匿名对象的函数属性?

时间:2015-05-14 09:14:16

标签: c# delegates system.reflection anonymous-class

我在这个领域非常新,所以每一个帮助都会受到欢迎。

所以我有这个匿名对象(不确定它的正确名称):

 var ERRORS = new
                {
                    ERROR   = new Func<bool>(() =>{ return true; })
                    , ERROR1  = new Func<bool>(() => { return true; })
                    , ERROR2  = new Func<bool>(() => { return true; })
                    , ERROR3  = new Func<bool>(() => { return true; })
                    , ERROR4  = new Func<bool>(() => { return true; })
                    , ERROR5  = new Func<bool>(() => { return true; })
                    , ERROR6  = new Func<bool>(() => { return true; })
                    , ERROR7  = new Func<bool>(() => { return true; })
                    , ERROR8  = new Func<bool>(() => { return true; })
                    , ERROR9  = new Func<bool>(() => { return true; })
                    , ERROR10 = new Func<bool>(() => { return true; })
                    , ERROR11 = new Func<bool>(() => { return true; })
                    , ERROR12 = new Func<bool>(() => { return true; })
                };

我想迭代这个对象属性并像函数一样调用它们。

到目前为止我已经制作了这段代码:

Type type = ERRORS.GetType();
MethodInfo[] properties = type.GetMethods();

foreach (MethodInfo property in properties)
{
    Delegate del = property.CreateDelegate(typeof(System.Func<bool>));
    Console.WriteLine("Name: " + property.Name + ", Value: " + del.Method.Invoke(ERRORS,null));                                                                                
}

这段代码是我在互联网上找到的,对它进行了一些调整,但它引发了异常:

  

“无法绑定到目标方法,因为其签名或安全透明度与委托类型的方法不兼容。”

这对我来说并不重要。

正如已经提到的,我是C#中的一个伟大的菜鸟,所以任何帮助都将受到赞赏。

2 个答案:

答案 0 :(得分:2)

您无法在匿名对象中创建方法。您只能拥有属性(可以是代理人)......

所以:

Type type = ERRORS.GetType();

// Properties:
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
    // Get the value of the property, cast it to the right type
    Func<bool> func = (Func<bool>)property.GetValue(ERRORS);

    // Call the delegate normally (`func()` in this case)
    Console.WriteLine("Name: " + property.Name + ", Value: " + func());
}

请注意,如果没有反射,您可以调用以下方法:

bool res = ERRORS.ERROR1();

Func<bool> func = ERRORS.ERROR1();
bool res = func();

请注意,一般来说,你所做的几乎是无用的,因为在定义它的函数之外传递匿名对象通常是错误的,并且在函数内部你已经知道它的“形状”(你知道它具有哪些属性) ,和他们的名字)

答案 1 :(得分:2)

是否真的有必要使用匿名类型+反射?为什么不是Func数组?

示例:

var errors = new Func<bool> [] 
{
    new Func<bool>(() => { return true; }),
    () => { return true; },
    () => { return true; },
    () => { return true; },
};

errors[0](); // take delegate by index and invoke