C# 获取bool类型的所有属性的值和名称

Rod*_*o R 0 c#

我试图获取类型为 bool 的所有属性的名称和值,似乎有效,但得到了错误的值。

这是我正在使用的代码:

signupItem.GetType().GetProperties()
    .Where(p => p.PropertyType == typeof(bool) && (bool) p.GetValue(signupItem, null))
    .Select(p => p.Name).ToList().ForEach(prop => {

    var value = (Boolean) signupItem.GetType()
    .GetProperty(prop).GetValue(signupItem, null);

    html = (value) ?
        html.Replace("{chkbox}", "<input type='checkbox' id='html' checked>") :
        html.Replace("{chkbox}", "<input type='checkbox' id='html'>");
    });
Run Code Online (Sandbox Code Playgroud)

示例:此处 - 值为真 值应该是真实的

但当尝试将其分配给变量时,它显示错误。

值显示为 false

任何帮助,将不胜感激。

D S*_*ley 5

  1. 不要使用.ForEach()
  2. 当您应该使用属性本身时,您正在选择每个属性的名称:
  3. 每次迭代都使用相同的html值,因此第一个循环将替换所有{chkbox}值。

尝试这个:

var properties = signupItem.GetType()
                           .GetProperties()
                           .Where(p => p.PropertyType == typeof(bool)
                                    && (bool) p.GetValue(signupItem, null));


foreach (Property prop in properties) {
    // don't you already know this is true from the `Where` clause?
    var value = (Boolean) prop.GetValue(signupItem, null);

    // this only happens for the first item - for all other items "{chkbox}" will already be replaced.
    html = (value) ?
        html.Replace("{chkbox}", "<input type='checkbox' id='html' checked>") :
        html.Replace("{chkbox}", "<input type='checkbox' id='html'>");
}    
Run Code Online (Sandbox Code Playgroud)