Consider the following object
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
}
Now what I am trying to achieve is set the property value to true
to all the bool
properties apart from RecordExist
and HasDamage
. To achieve this I have gone ahead and created the following method.
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;
}
The above method is then called as follows:
public Foo Foo()
{
string[] propsToExclude = new string[]
{
"RecordExist",
"HasDamage"
};
var foo = SetBoolPropertyValueOfObject<Foo>(propsToExclude, typeof(bool), true);
return foo;
}
The method does not work as expected. When inside the foreach
loop first time the RecordExist
prop is set to false but when it goes into the loop again RecordExist
is set to true and the rest of the props are set to true as well including HasDamage
.
Can someone tell me where I am going wrong please.
Aucun commentaire:
Enregistrer un commentaire