动态获取、设置类的属性
1、获取属性
// 遍历 ChangeSystemSettingDto 的所有属性
foreach (var propertyInfo in typeof(ChangeSystemSettingDto).GetProperties())
{
// 获取属性名称和值
var propertyName = propertyInfo.Name;
var propertyValue = propertyInfo.GetValue(input);
}
2、设置属性
public async Task<ChangeSystemSettingDto> GetSystemSetting()
{
// 创建一个 MyDto 实例
ChangeSystemSettingDto systemSettingDto = new ChangeSystemSettingDto();
// 遍历 ChangeSystemSettingDto 的所有属性并为其赋值
foreach (var propertyInfo in typeof(ChangeSystemSettingDto).GetProperties())
{
// 获取属性名称和类型
var propertyName = propertyInfo.Name;
// 获取 常量字段并读取其值
var stringValueField = myStaticClassType.GetField(propertyName);
var stringValue = (string)stringValueField.GetValue(null);
//获取setting 值
propertyInfo.SetValue(systemSettingDto, "设置值");
}
return systemSettingDto;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步