[英]How to iterate through limited set of instance properties?
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...
}
When wrapping it in an object[]
you can get all values, but you loose the knowledge of the property behind it. 将它包装在一个
object[]
你可以得到所有的值,但是你不知道它背后的属性。
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: 您可以使用
Dictionary
代替:
When wrapping it in an object[]
you can get all values, but you loose the knowledge of the property behind it. 将它包装在一个
object[]
你可以得到所有的值,但是你不知道它背后的属性。
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
: 理想情况下,在下一版本的c#中,您可以使用
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.