Get property-name of generic abstract class

纵饮孤独 提交于 2019-12-10 10:05:25

问题


Considering the following implementation of a generic, abstract class:

public abstract class BaseRequest<TGeneric> : BaseResponse where TRequest : IRequestFromResponse
{
    public TGeneric Request { get; set; }
}

Is there any chance to get the name of the property Request without having an instance inherited from it?

I need Request as string "Request" to avoid using hardcoded strings. Any ideas how to make this through reflection?


回答1:


Starting from C# 6, you should be able to use the nameof operator:

string propertyName = nameof(BaseRequest<ISomeInterface>.Request);

The generic type parameter used for BaseRequest<T> is irrelevant (as long as it meets the type constraints), since you are not instantiating any object from the type.

For C# 5 and older, you can use Cameron MacFarland's answer for retrieving property information from lambda expressions. A heavily-simplified adaptation is given below (no error-checking):

public static string GetPropertyName<TSource, TProperty>(
    Expression<Func<TSource, TProperty>> propertyLambda)
{
    var member = (MemberExpression)propertyLambda.Body;
    return member.Member.Name;
}

You can then consume it like so:

string propertyName = GetPropertyName((BaseRequest<ISomeInterface> r) => r.Request);
// or //
string propertyName = GetPropertyName<BaseRequest<ISomeInterface>, ISomeInterface>(r => r.Request);



回答2:


Can you elaborate a little more on what it is you're trying to achieve? It looks like you're making requests to web API, for what purpose are you wanting the name of the property and in what context?

This will get you the names of all of the properties in an object type:

var properties = typeof(MyClass).GetProperties(BindingFlags.Public | BindingFlags.Static).Select(p => p.Name);


来源:https://stackoverflow.com/questions/31636725/get-property-name-of-generic-abstract-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!