将对象名称空间和名称转换为对象
|
我需要调用
SetSettings()
并使用splitSettings
中的3个元素,将EncodeAudio
设置为False
。
我将如何去做?将对象的属性转换为我在字符串中具有的姓名。
我意识到我可以使用所有设置的switch语句来做,但是必须有一种更动态的方式来执行此操作。
namespace SettingsLib
{
public class Settings
{
public Boolean EncodeAudio { get; set; }
}
}
namespace Service
{
void SetSettings()
{
string[] splitSettings = { \"SettingsLib.Settings\", \"EncodeAudio\", \"False\" };
// Need to set EncodeAudio to False in SettingsLib.Settings
}
}
是的,我有一个设置实例
说:
Settings settingManager = new Settings();
我正在尝试通过使用splitSettings的元素将EncodeAudo动态设置为False
settingManager.EncodeAudio = False;
感谢TBohnen.jnr的帮助
我来到这个答案:
public void setProperty(object containingObject, string propertyName, object newValue)
{
foreach (PropertyInfo p in containingObject.GetType().GetProperties())
{
if (p.Name == propertyName)
{
p.SetValue(containingObject, Convert.ChangeType(newValue, p.PropertyType), null);
}
}
}
没有找到相关结果
已邀请:
3 个回复
貉骂
取自http://www.haslo.ch/blog/setproperty-and-getproperty-with-c-reflection/ 有兴趣查看是否可行,请创建一个快速测试:
输出为true,但不确定是否会正确转换所有类型。
亲奋漏
提孺局缎
,然后尝试使用Reflection设置值: