使用反射在静态类上设置属性

30

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

我试着使用以下代码,但我不知道要给SetValue方法传递什么参数,因为我们要设置属性的类是静态的。

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

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;
    }
}

使用反射是否可以设置静态类的属性?


“Settings” 是什么意思?**internal sealed partial class Settings**是一个类吗? - PreguntonCojoneroCabrón
1个回答

45

只需将实例传递 null 值即可。


1
根据文档,它会被忽略,因此您可以传递任何内容。为了可读性,我们通常这样调用:prop.SetValue("ThisArgumentIsIgnoredForStaticMethods", value); - Jan Van der Haegen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接