【问题标题】:How to Invoke dynamicaly an anonymus objects function property?如何动态调用匿名对象函数属性?
【发布时间】:2015-05-14 09:14:15
【问题描述】:

我是这个领域的新手,所以欢迎任何帮助。

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

 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# 方面的优秀菜鸟,因此我们将不胜感激。

【问题讨论】:

  • 真的有必要使用匿名类型+反射吗?为什么不是 Func 的数组?
  • 可以正常工作,但仍然必须调用它们。我做错了:)

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


【解决方案1】:

您不能在匿名对象中创建方法。您只能拥有属性(可以是委托)...

所以:

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

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

【讨论】:

    【解决方案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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-18
      • 2011-11-30
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多