Reputation: 27
I have a class with huge number of properties but I want to alter only several of them. Could you suggest me how to implement functionality below:
var model = session.Load<MyType>(id);
foreach(var property in [model.RegistrationAddress, model.ResidenceAddress, model.EmploymentAddress, model.CorrespondenceAddress])
{
// alter each of the given properties...
}
Upvotes: 0
Views: 95
Reputation: 157116
When wrapping it in an object[]
you can get all values, but you loose the knowledge of the property behind it.
foreach( var property in
new object[]
{ model.RegistrationAddress
, model.ResidenceAddress
, model.EmploymentAddress
, model.CorrespondenceAddress
}
)
{
// alter each of the given properties...
}
You can use a Dictionary
instead:
When wrapping it in an object[]
you can get all values, but you loose the knowledge of the property behind it.
foreach( KeyValuePair<string, object> property in
new Dictionary<string, object>
{ { "RegistrationAddress", model.RegistrationAddress}
, { "ResidenceAddress", model.ResidenceAddress } ...
}
)
{
// alter each of the given properties...
}
Ideally, in the next version of c#, you can use nameof
:
new Dictionary<string, object>
{ { nameof(RegistrationAddress), model.RegistrationAddress}
, { nameof(ResidenceAddress), model.ResidenceAddress } ...
}
When you need to set the parameters, you can use something like this:
public class GetSet<T>
{
public GetSet(Func<T> get, Action<T> set)
{
this.Get = get;
this.Set = set;
}
public Func<T> Get { get; set; }
public Action<T> Set { get; set; }
}
Call it like this:
ClassX x = new ClassX();
foreach (var p in new GetSet<string>[] { new GetSet<string>(() => { return x.ParameterX; }, o => { x.ParameterX = o; }) })
{
string s = p.Get();
p.Set("abc");
}
Upvotes: 2