【发布时间】: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;
}
}
甚至可以通过反射在静态类上设置属性吗?
【问题讨论】:
-
Settings是internal sealed partial class Settings?
标签: c# reflection static