使用字符串值自动链接字符串到属性

本文关键字:字符串 链接 属性 | 更新日期: 2023-09-27 18:06:01

这可能是一个愚蠢的问题,但我要把它拍出来。

例如我有一个模型类:

public class PermissionModel
{
    public bool AppName_Home_Product_SaveButton_Enabled { get; set; }
    public bool AppName_Home_Product_ConfirmButton_Enabled { get; set; }
}

我有以下字符串列表:

"AppName_Home_Product_SaveButton_Enabled_true"
"AppName_Home_Product_SaveButton_Enabled_false"

我想用true/false自动填充模型属性,而不必像下面的例子那样使用if语句:

if (aString.Contains("AppName_Home_Product_SaveButton_Enabled"))
{       
    PermissionModel.AppName_Home_Product_SaveButton_Enabled = Convert.ToBoolean(AString.Substring(AString.IndexOf("Enabled_") + 8));
}

有什么想法吗?还是这太疯狂了?我只是想避免一堆if语句来填充模型,使其更易于重用。

使用字符串值自动链接字符串到属性

这可以通过反射来实现

const string delimiter = "_Enabled";
foreach (string data in aString) {
  int index = data.IndexOf(delimiter);
  if (index >= 0) {
    // Get the name and value out of the data string 
    string name = data.Substring(0, index + delimiter.Length);
    bool value = Convert.ToBoolean(data.Substring(index + delimiter.Length + 1));
    // Find the property with the specified name and change the value
    PropertyInfo  property = GetType().GetProperty(name);
    if (property != null) {
      property.SetValue(this, value);
    }
  }
}