使用静态类的反射设置属性

mar*_*are 23 c# reflection static

我想创建一个静态类,它将从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;
        }
Run Code Online (Sandbox Code Playgroud)

}

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

lep*_*pie 36

只是传递null给实例.

  • 使用"typeof(设置)"代替"this"也可以 (2认同)