【问题标题】:Setting properties with reflection on static classes在静态类上使用反射设置属性
【发布时间】:2010-08-11 16:47:33
【问题描述】:

我想创建一个静态类,它会从 XML 文件加载一些设置并将这些设置应用到它自己的属性中。

我正在尝试使用以下代码,但我真的不知道要为 SetValue 方法提供什么,因为我们要为其设置属性的类是静态的。

// some code removed ...
Type settingsType = typeof(Settings);   // Settings is a static class

foreach (PropertyInfo propertyInformation in settingsType.GetProperties(BindingFlags.Public |
                                  BindingFlags.Static))
{
        //------------------------------------------------------------
        //  Determine if configured setting matches current setting based on name
        //------------------------------------------------------------
        if (propertyInformation.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
        {
        //------------------------------------------------------------
        //  Attempt to apply configured setting
        //------------------------------------------------------------
        try
        {
        if (propertyInformation.CanWrite)
        {
        propertyInformation.SetValue(this, Convert.ChangeType(value, propertyInformation.PropertyType, CultureInfo.CurrentCulture), null);
        }
        }
        catch
        {
        }
            break;
        }

}

甚至可以通过反射在静态类上设置属性吗?

【问题讨论】:

  • Settingsinternal sealed partial class Settings ?

标签: c# reflection static


【解决方案1】:

只需为实例传递null

【讨论】:

  • @mare:静态成员可能会忽略它。
  • 根据文档,它被忽略了,所以你可以传递任何东西。为了可读性,我们通常这样称呼它:``` prop.SetValue("ThisArgumentIsIgnoredForStaticMethods", value); ```
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 2011-09-20
  • 1970-01-01
  • 2010-10-01
  • 1970-01-01
相关资源
最近更新 更多