获取通用抽象类的属性名称

Kin*_*sin 3 c# generics reflection abstract-class naming-conventions

考虑以下通用抽象类的实现:

public abstract class BaseRequest<TGeneric> : BaseResponse where TRequest : IRequestFromResponse
{
    public TGeneric Request { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

有没有机会获得属性的名称Request而没有从中继承的实例?

我需要Request字符串"Request"来避免使用硬编码字符串.任何想法如何通过反思来做到这一点?

Dou*_*las 6

从C#6开始,您应该能够使用nameof运算符:

string propertyName = nameof(BaseRequest<ISomeInterface>.Request);
Run Code Online (Sandbox Code Playgroud)

用于的泛型类型参数BaseRequest<T>是无关紧要的(只要它满足类型约束),因为您没有从类型中实例化任何对象.

对于C#5及更早版本,您可以使用Cameron MacFarland的答案从lambda表达式中检索属性信息.下面给出了一个非常简化的适应(没有错误检查):

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

然后您可以像这样使用它:

string propertyName = GetPropertyName((BaseRequest<ISomeInterface> r) => r.Request);
// or //
string propertyName = GetPropertyName<BaseRequest<ISomeInterface>, ISomeInterface>(r => r.Request);
Run Code Online (Sandbox Code Playgroud)