[英]How to iterate through limited set of instance properties?
我有一個具有大量屬性的類,但我想只改變其中的幾個。 你能建議我如何實現以下功能:
var model = session.Load<MyType>(id);
foreach(var property in [model.RegistrationAddress, model.ResidenceAddress, model.EmploymentAddress, model.CorrespondenceAddress])
{
// alter each of the given properties...
}
將它包裝在一個object[]
你可以得到所有的值,但是你不知道它背后的屬性。
foreach( var property in
new object[]
{ model.RegistrationAddress
, model.ResidenceAddress
, model.EmploymentAddress
, model.CorrespondenceAddress
}
)
{
// alter each of the given properties...
}
您可以使用Dictionary
代替:
將它包裝在一個object[]
你可以得到所有的值,但是你不知道它背后的屬性。
foreach( KeyValuePair<string, object> property in
new Dictionary<string, object>
{ { "RegistrationAddress", model.RegistrationAddress}
, { "ResidenceAddress", model.ResidenceAddress } ...
}
)
{
// alter each of the given properties...
}
理想情況下,在下一版本的c#中,您可以使用nameof
:
new Dictionary<string, object>
{ { nameof(RegistrationAddress), model.RegistrationAddress}
, { nameof(ResidenceAddress), model.ResidenceAddress } ...
}
當您需要設置參數時,您可以使用以下內容:
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; }
}
像這樣稱呼它:
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.