开发者

C#: Given src => src.property, code choosing property if you have a string "propertyname"?

开发者 https://www.devze.com 2023-01-22 21:42 出处:网络
I am using AutoMapper where it has:开发者_运维知识库 .ForMember( dest => dest.id, opt => opt.MapFrom(src => src.id))

I am using AutoMapper where it has:开发者_运维知识库

.ForMember( dest => dest.id, opt => opt.MapFrom(src => src.id))

Using the far right expression src => src.id, if I have a string variable with the property's name, how would I choose the property by it?

I tried this:

src => propertyName

Then had to laugh when the value was "id".


You can use reflection to get a property by name:

private R GetProperty<T, R>(T obj, string propertyName)
{
    PropertyInfo pi = obj.GetType().GetProperty(propertyName);
    return (R)pi.GetValue(obj, null);
}

Which you would use in AutoMapper like this:

.ForMember( dest => dest.id, opt => opt.MapFrom(src => GetProperty(src, propertyName)))


If you have the name of the property you wish to access, you would use reflection to get MemberInfo and then invoke the property from the MemberInfo.

src => src.GetType().GetProperty(propertyName).GetGetMethod().Invoke(src, new object[] {})

Of course, this tidbit assumes src has properties and that propertyName identifies a property on the object.

0

精彩评论

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