首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在静态类上使用反射设置属性

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

Stack Overflow用户
提问于 2010-08-12 00:47:33
回答 1查看 10.6K关注 0票数 26

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

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

代码语言:javascript
复制
// 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;
        }

}

有没有可能用反射来设置静态类的属性?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-08-12 00:49:12

只需传递实例的null即可。

票数 41
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3460745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档