【问题标题】:How to invoke method, using reflection, on instantiated object?如何在实例化对象上使用反射调用方法?
【发布时间】:2009-10-01 00:49:53
【问题描述】:

我有一些基础对象“汽车”、“狗”、“猫”,它们实现了一个接口“IGWUIElement”。我有这些接口的列表:List myList。

在运行时,我循环遍历我的元素列表并通过检查类的名称(使用反射),我需要填充它们的属性 - 这不是接口的一部分)。我有一个描述属性和我应该分配给它们的值的 xml 文档。这是我的接口实例化。

IGWUIElement newUIElement = (IGWUIElement)Activator.CreateInstance(result);

如何使用特定值从它们的名称中调用属性(请注意数据类型仅限于 int 和 string)。每个对象都有不同的属性。

希望这是有道理的......

/H4mm3r

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    使用 PropertyInfo.SetValue()

    PropertyInfo piInstance = typeof(IGWUIElement).GetProperty("property_name");
    piInstance.SetValue(newUIElement, value, null);
    

    更多关于msdn

    【讨论】:

      【解决方案2】:

      你可以这样做:

      IGWUIElement element = myList[0];
      
      // Set a string property
      element.GetType().InvokeMember("SomeStringProperty", BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, element, "The String Value");
      
      // Set an int property
      element.GetType().InvokeMember("SomeIntProperty", BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, element, 3);
      

      【讨论】:

        猜你喜欢
        • 2010-11-30
        • 1970-01-01
        • 1970-01-01
        • 2018-11-06
        • 2023-04-05
        • 2011-02-15
        • 1970-01-01
        • 2021-11-30
        • 1970-01-01
        相关资源
        最近更新 更多