问题描述
考虑以下通用抽象类的实现:
Considering the following implementation of a generic, abstract class:
public abstract class BaseRequest<TGeneric> : BaseResponse where TRequest : IRequestFromResponse
{
public TGeneric Request { get; set; }
}
是否有机会获得属性Request
的名称而又没有从其继承实例?
Is there any chance to get the name of the property Request
without having an instance inherited from it?
我需要Request
作为字符串"Request"
,以避免使用硬编码的字符串.有什么想法可以通过反思做到这一点吗?
I need Request
as string "Request"
to avoid using hardcoded strings. Any ideas how to make this through reflection?
推荐答案
从C#6开始,您应该能够使用nameof
运算符:
Starting from C# 6, you should be able to use the nameof
operator:
string propertyName = nameof(BaseRequest<ISomeInterface>.Request);
用于BaseRequest<T>
的通用类型参数是无关紧要的(只要它符合类型约束),因为您没有从该类型实例化任何对象.
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.
对于C#5和更早版本的C#,您可以使用 Cameron MacFarland的答案来从lambda表达式中检索属性信息.下面给出了一个大大简化的改编(无错误检查):
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);
这篇关于获取通用抽象类的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!