对于属性/方法/成员,是否有类似于C#的typeof?

Type元数据可以通过多种方式获得。 其中两个是:

var typeInfo = Type.GetType("MyClass")

var typeInfo = typeof(MyClass)

第二种方式的优点是编译器会捕获拼写错误,并且IDE可以理解我正在谈论的内容(允许重构等function而不会无声地破坏代码)

是否存在强烈引用元数据和reflection的成员/属性/方法的等效方法? 我可以更换:

var propertyInfo = typeof(MyClass).GetProperty("MyProperty")

有类似的东西:

var propertyInfo = property(MyClass.MyProperty)

不,不幸的是没有。 它已被讨论甚至命名: infoof (发音为“in-foof”的喜剧价值),但尚未实施…… Eric Lippert有一篇关于它的博客文章 。

你可以在C#3中最接近的是让编译器生成一个表达式树,然后将其拉出来 – 但这并不令人愉快。

我刚刚使用Syste.Linq.Expressions实现了”fieldof”fieldof’方法的构造’propertyof’

所以不要写作

 var mi = typeof (string).GetMethod("Concat", new[] {typeof (object), typeof (object)}); 

您可以使用:

 var mi = ReflectionHelper.MethodOf(() => string.Concat(new object(), new object())); 

我们为什么需要这个? 因为现在我们可以安全地重构方法,我们使用viareflection

帮助类的列表(您可能需要在方法中添加一些信息性exception):

 ///  /// Represents a set of helpers for .net reflection ///  public static class ReflectionHelper { #region Public methods ///  /// Gets a MethodInfo object from specified expression ///  ///  ///  ///  public static MethodInfo MethodOf(Expression> methodExpression) { return ((MethodCallExpression)methodExpression.Body).Method; } ///  /// Gets a MethodInfo object from specified expression ///  ///  ///  public static MethodInfo MethodOf(Expression methodExpression) { return ((MethodCallExpression)methodExpression.Body).Method; } ///  /// Gets a MethodInfo object from specified expression ///  ///  ///  public static MethodInfo MethodOf(Expression> methodExpression) { return ((MethodCallExpression)methodExpression.Body).Method; } ///  /// Gets a MethodInfo object from specified expression ///  ///  ///  public static MethodInfo MethodOf(Expression> methodExpression) { return ((MethodCallExpression)methodExpression.Body).Method; } ///  /// Gets a PropertyInfo object from specified expression ///  ///  ///  public static PropertyInfo PropertyOf(Expression> propertyGetExpression) { return ((MemberExpression)propertyGetExpression.Body).Member as PropertyInfo; } ///  /// Gets a PropertyInfo object from specified expression ///  ///  ///  public static PropertyInfo PropertyOf(Expression> propertyGetExpression) { return ((MemberExpression)propertyGetExpression.Body).Member as PropertyInfo; } ///  /// Gets a FieldInfo object from specified expression ///  ///  ///  public static FieldInfo FieldsOf(Expression> fieldAccessExpression) { return ((MemberExpression)fieldAccessExpression.Body).Member as FieldInfo; } //TODO: ConstructorOf(...) #endregion //Public methods } 

据我所知,我们无法使用相同的aproach来获取getParameterInfo或EventInfo

另一种方法,由Jb Evain描述,请参阅: http ://evain.net/blog/articles/2010/05/05/parameterof-propertyof-methodof?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+jbevain+%28Jb 在+ + A +简而言之%29

在c#6中仍然没有infoof但有nameof

 var propertyInfo = typeof(MyClass).GetProperty(nameof(MyClass.MyProperty)) 

它肯定不是更简洁,但至少它的重构是友好的。

不,c#中没有这样的语法。