How to assign values ​​to several properties of a class, for example, a list of elements used for a loop?

I want to set a list of properties at the same time, is this possible? Thanks!

public class Helper { public bool A { get; set; } public bool B { get; set; } public bool C { get; set; } public void SetToFalse(List<Property> ABC) { // try to set A, B, C to false in a for loop foreach (var item in ABC) { item = false; } } } 

Why I want to do this: I want to have a clean way to switch logical properties at the same time, while I cannot group properties into a list, because the context is ViewModel and the properties are bound to Xaml.

+4
source share
4 answers

I would use rambda list.

 public class Helper { public bool A { get; set; } public bool B { get; set; } public bool C { get; set; } public List<Action<bool>> Setters { get; set; } public Helper() { this.Setters = new List<Action<bool>>() { b => this.A = b, b => this.B = b, b => this.C = b }; } public void SetToFalse(IEnumerable<Action<bool>> setters) { // try to set A, B, C to false in a for loop foreach (var a in setters) { a(false); } } } 

Do you like this?

+1
source

That should work.

 Helper helper = new Helper(); //This will get all Boolean properties of your class var properties = helper.GetType().GetProperties().Where(e=>e.PropertyType==typeof(Boolean)); //Completing all Boolean properties with "false" foreach (var propertyInfo in properties) { propertyInfo.SetValue(helper,false); } 

Note - using reflection at runtime is a bad move (performance decreases)

0
source

If you need to support a lot of logical flags, I would change it to a dictionary and do something like this:

 class Class1 { private Dictionary<String, Boolean> boolenVars = new Dictionary<String, Boolean>(); public Boolean getFlag(String key) { if (this.boolenVars.ContainsKey(key)) return this.boolenVars[key]; else return false; } public void setFlag(String key, Boolean value) { if (this.boolenVars.ContainsKey(key)) this.boolenVars[key] = value; else this.boolenVars.Add(key, value); } public void clearFlags() { this.boolenVars.Clear(); } } 

Instead of using a string key, you can create an enumeration for this purpose to ensure that there are no typos when using flags.

This solution will not require any additional code changes, even if you decide to add 7526 new Boolean Flags.

This solution also provides - if you expose the dictionary using the public getter method or method - a list of all the "set" logical flags.

0
source

You can use object initializers for this. VS will give you intellisense for properties.

http://msdn.microsoft.com/en-us/library/vstudio/bb384062.aspx

Example:

 class Helper { public bool A { get;set;} public bool B { get;set;} } Helper myclass = new Helper { A = false, B = false }; 

This does not use a for loop, but in my opinion it is cleaner.

-one
source

Source: https://habr.com/ru/post/1492638/


All Articles