获取泛型抽象类的属性名

本文关键字:属性 抽象类 泛型 获取 | 更新日期: 2023-09-27 18:04:48

考虑以下泛型抽象类的实现:

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

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

我需要Request作为字符串"Request",以避免使用硬编码字符串。有什么想法可以通过反射来实现吗?

获取泛型抽象类的属性名

从c# 6开始,您应该能够使用nameof操作符:

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

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;
}

你可以这样使用它:

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

你能详细说明一下你想要达到的目标吗?看起来你正在向web API发出请求,你想要属性的名称是为了什么目的,在什么上下文中?

这将为您提供对象类型中所有属性的名称:

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