【问题标题】:C# Reflection - Get PropertyInfo without a string [duplicate]C# 反射 - 获取没有字符串的 PropertyInfo [重复]
【发布时间】:2013-11-09 22:04:15
【问题描述】:

我在Myclass有一处房产:

public class MyClass{    
    public string FirstName {get;set;}
}

如何在没有字符串的情况下获得PropertyInfo(使用GetProperty("FirstName"))?

今天我用这个:

PropertyInfo propertyTitleNews = typeof(MyClass).GetProperty("FirstName");

有没有这样的使用方法:

PropertyInfo propertyTitleNews = typeof(MyClass).GetProperty(MyClass.FirstName);

?

【问题讨论】:

  • 似乎如果您可以访问类的属性,那么您就不需要反射开始了。如果这是 .NET 4 或更高版本,您是否尝试过使用 Dynamic 关键字?
  • 是的,有可能。 look at this answer.
  • 我同意洛克的观点。这没有多大意义。当您创建属性的唯一方法是从字符串中时,您通常会使用反射。
  • @Szymon 不,一般来说它确实有意义,因为PropertyInfo 拥有的信息不仅仅是属性的类型及其值。
  • 当心所有涉及成员表达式的答案。有一个绊倒的角落案例:stackoverflow.com/questions/6658669/…!这样做不是很安全

标签: c# reflection


【解决方案1】:

here。这个想法是使用表达式树。

public static string GetPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
{
    MemberExpression body = (MemberExpression)expression.Body;
    return body.Member.Name;
}

然后像这样使用它:

var name = GetPropertyName<MyClass, string>(c => c.FirstName);

一个更简洁的解决方案是如果不需要指定这么多通用参数。并且可以通过将 MyClass 通用参数移动到 util 类来实现:

public static class TypeMember<T>
{
    public static string GetPropertyName<TReturn>(Expression<Func<T, TReturn>> expression)
    {
        MemberExpression body = (MemberExpression)expression.Body;
        return body.Member.Name;
    }
}

然后使用会更干净:

var name = TypeMember<MyClass>.GetPropertyName(c => c.FirstName);

【讨论】:

  • 是否可以在没有 lambda 开销的情况下做到这一点?
  • @rolls 你是什么意思? lambda 永远不会执行,因此它只是编译器传递的数据。 lambda 也不捕获任何本地变量,因此也没有额外的分配。
  • 好点。我没有仔细考虑过它,这与传入一个对象/结构并没有太大区别。
【解决方案2】:

除了Ivan Danilov's answer之外,另一种可能是提供扩展方法:

public static class PropertyInfoExtensions
{
    public static string GetPropertyName<TType, TReturnType>(
        this TType @this,
        Expression<Func<TType, TReturnType>> propertyId)
    {
        return ((MemberExpression)propertyId.Body).Member.Name;
    }
}

然后像这样使用它:

MyClass c;
PropertyInfo propertyTitleNews = c.GetPropertyName(x => x.FirstName);

缺点是您需要一个实例,但优点是您不需要提供泛型参数。

【讨论】:

    【解决方案3】:

    你可以这样做

    var property = ExpressionExtensions.GetProperty<MyClass>(o => o.FirstName);
    

    有了这个助手:

    public static PropertyInfo GetProperty<T>(Expression<Func<T, Object>> expression)
    {
         MemberExpression body = (MemberExpression)expression.Body;
         return typeof(T).GetProperty(body.Member.Name);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      相关资源
      最近更新 更多