CreateDelegate On扩展方法

时间:2011-05-13 09:57:01

标签: c# extension-methods

我有一个具有IList只读属性的类。我创建了一个简单的扩展方法AddCSV,以向该列表添加多个项目。我想创建一个动作委托,通过扩展方法填充列表。到目前为止,我有

private Action<TListPropertyContainer, TDataValue> CreateListPropertySetter<TListPropertyContainer, TDataValue>(string listName)
{
    var list = typeof(TListPropertyContainer).GetProperty(listName);
    var method = typeof(Extensions).GetMethod("AddCSV");
    return (Action<TListPropertyContainer, TDataValue>)Delegate.CreateDelegate(typeof(Action<TListPropertyContainer, TDataValue>), list, method);
}

但显然这不起作用!

我知道还有其他选择。例如 a)我可以将列表继承到我自己的客户类中,并在那里添加AddCSV b)我可以将items属性读/写,并将完全填充的列表设置到我的类

如果有人能纠正我,我将不胜感激。

很多thx

西蒙

2 个答案:

答案 0 :(得分:2)

有两个主要问题。

  1. 您正尝试在PropertyInfo上调用该方法,而不是列表。要获取该属性的值,您需要调用GetValue()

  2. GetMethod()的调用未指定绑定标志。我怀疑它可能会更好用GetMethod("AddCSV", BindingFlags.Public | BindingFlags.Static)

  3. 话虽如此,当你事先知道类型和方法时,为什么要反思性地实例化它?看起来你可以做到:

     private Action<TListPropertyContainer, TDataValue> CreateListPropertySetter<TListPropertyContainer, TDataValue>(string listName)
     {
           var propertyInfo = typeof(TListPropertyContainer).GetProperty(listName);
           return (container,value) => {
                var list = (IList<TDataValue>)propertyInfo.GetValue(container,null);
                list.AddCSV(list);
           };
      }
    

    如果我对扩展方法的签名或属性类型做出错误的假设,您仍然可以使用Delegate.CreateDelegate()执行此操作,但请对PropertyInfo和{{1考虑到帐户

答案 1 :(得分:1)

您尝试使用list作为代理人的目标 - 但list的类型为PropertyInfo,听起来像是而不是你是什么的期待着。假设您想要获取属性的,然后在其上调用方法,您还需要传入包含该属性的对象,这样您就可以获得实际的列表。 (或者,也许它是“这个” - 你还没有真正说清楚。)无论哪种方式,你都可以获得列表本身并使用 作为目标。例如:

private Action<TListPropertyContainer, TDataValue> 
    CreateListPropertySetter<TListPropertyContainer, TDataValue>
    (string listName, object target)
{
    var listProperty = typeof(TListPropertyContainer).GetProperty(listName);
    object list = listProperty.GetValue(target, null);
    var method = typeof(Extensions).GetMethod("AddCSV");
    return (Action<TListPropertyContainer, TDataValue>)Delegate.CreateDelegate(
        typeof(Action<TListPropertyContainer, TDataValue>), list, method);
}

如果这样做无效,请使用简短但完整的控制台应用程序编辑您的问题,以证明问题所在。现在有太多的未知数值可以帮助你。

相关问题