设置对象的所有bool属性值

Izz*_*zzy 1 c# reflection

考虑以下对象

public class Foo
{
    public bool RecordExist { get; set; }

    public bool HasDamage { get; set; }

    public bool FirstCheckCompleted { get; set; }

    public bool SecondCheckCompleted { get; set; }

    //10 more bool properties plus other properties
}
Run Code Online (Sandbox Code Playgroud)

现在我想要实现的是将属性值设置为除和之外的true所有bool属性.为实现这一目标,我已经开始创建以下方法.RecordExistHasDamage

public T SetBoolPropertyValueOfObject<T>(string[] propNames, Type propertyType, object value)
{
   PropertyInfo[] properties = typeof(T).GetProperties();

   T obj = (T)Activator.CreateInstance(typeof(T));

    if(propNames.Length > 0 || propNames != null)
        foreach (var property in properties)
         foreach (string pName in propNames)
            if (property.PropertyType == propertyType && property.Name != pName)
                 property.SetValue(obj, value, null);

        return obj;
}
Run Code Online (Sandbox Code Playgroud)

然后按如下方式调用上述方法:

public Foo Foo()
{
   string[] propsToExclude = new string[]
   {
      "RecordExist",
      "HasDamage"
   };

    var foo = SetBoolPropertyValueOfObject<Foo>(propsToExclude, typeof(bool), true);

    return foo;
}
Run Code Online (Sandbox Code Playgroud)

该方法无法按预期工作.当内foreach环路首次RecordExist道具设置为false,但是当它进入循环再RecordExist设置为true和道具的剩余部分都设置为true,以及包括HasDamage.

请问有人告诉我哪里出错了.

Ren*_*ogt 5

你的逻辑错了:

  • 外循环想要设置例如 RecordExist
  • 内循环,第一步说"哦,它等于RecordExist,我没有设置"
  • 内循环,第二步:"哦RecordExist不等于HasDamage我设置"

您只想知道是否propNames 包含属性名称:

if(propNames.Length > 0 || propNames != null)
      foreach (var property in properties)
          if (property.PropertyType == propertyType && 
              !propNames.Contains(property.Name))
             property.SetValue(obj, value, null);
Run Code Online (Sandbox Code Playgroud)

但请注意,如果您提供要排除的名称(外部if),则这仅设置任何属性.我不认为这就是你想要的.

所以最终的代码可能如下所示:

foreach (var property in properties.Where(p => 
                p.PropertyType == propertyType &&
                propNames?.Contains(p.Name) != true)) // without the 'if' we need a null-check
     property.SetValue(obj, value, null);
Run Code Online (Sandbox Code Playgroud)