开发者

How set property name/value dynamically?

Hi I'm not sure if I'm describing it p开发者_如何转开发roperly, but based on a list of strings, I want to set the values of properties that belong to an object (all properties, which are objects, that match the string names):

var _parentObject = _parentObjectService.GetParentObject(viewModel.Id);
var _listOfPropertyNames = GetPropertyNames();

foreach (var item in _listOfPropertyNames)
{
// Pseudo code, I know it's gibberish:
_parentObject.Tests.[item] = viewModel.Tests.[item];

}

Hopefully that makes sense, please let me know if not.

Thank you.


It sounds like you're looking for AutoMapper, which will do all this for you:

//Once:
Mapper.CreateMap<FromType, ToType>();

//Then:
Mapper.Map(viewModel.Tests, _parentObject.Tests);

If you want to do it yourself, you'll need reflection (slow) or compiled expression trees (fast).


Use reflection to set the property value, as per: Set object property using reflection

Really simple example:

void SetParamByName(object obj, string paramName, object value)
{
    obj.GetType()
        .InvokeMember(
            paramName,
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
            Type.DefaultBinder,
            obj,
            value
        );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜