如何迭代有限的实例属性集?

时间:2014-05-12 14:04:45

标签: c# linq class foreach

我有一个具有大量属性的类,但我想只改变其中的几个。你能否建议我如何实现以下功能:

var model = session.Load<MyType>(id);

foreach(var property in [model.RegistrationAddress, model.ResidenceAddress, model.EmploymentAddress, model.CorrespondenceAddress])
{
    // alter each of the given properties...
}

1 个答案:

答案 0 :(得分:2)

将它包装在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");
}