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)
}
甚至可以使用反射在静态类上设置属性吗?