简体   繁体   English

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

[英]Is there a C# equivalent of typeof for properties/methods/members?

A classes Type metadata can be obtained in several ways.可以通过多种方式获得类的Type元数据。 Two of them are:其中两个是:

var typeInfo = Type.GetType("MyClass")

and

var typeInfo = typeof(MyClass)

The advantage of the second way is that typos will be caught by the compiler, and the IDE can understand what I'm talking about (allowing features like refactoring to work without silently breaking the code)第二种方式的优点是拼写错误会被编译器捕获,IDE 可以理解我在说什么(允许重构等功能在不默默破坏代码的情况下工作)

Does there exist an equivalent way of strongly referencing members/properties/methods for metadata and reflection?是否存在强烈引用元数据和反射的成员/属性/方法的等效方法? Can I replace:我可以更换:

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

with something like:像这样:

var propertyInfo = property(MyClass.MyProperty)

No, unfortunately not.不,不幸的是没有。 It's been discussed and even named: infoof (pronounced "in-foof" for comedy value) but it's not been implemented... yet.它已经被讨论过,甚至被命名为: infoof (在喜剧价值中发音为“in-foof”),但它还没有被实施……还没有。 Eric Lippert has a blog post about it . Eric Lippert 有一篇关于它博客文章

The closest you can come in C# 3 is to make the compiler generate an expression tree, and then pull it out of that - but that's hardly pleasant.在 C# 3 中最接近的是让编译器生成一个表达式树,然后将它拉出来 - 但这并不令人愉快。

I've just implemented an equivalent of constructions 'propertyof' 'methodof' 'fieldof' using Syste.Linq.Expressions我刚刚使用 Syste.Linq.Expressions 实现了一个等效的结构 'propertyof' 'methodof' 'fieldof'

so instead of writing所以而不是写作

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

you can use:您可以使用:

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

Why do we need this?我们为什么需要这个? because now we safe to refactor method, we use via reflection因为现在我们可以安全地重构方法,我们使用通过反射

listing of helper class (you may need to add some informative exceptions in methods):辅助类列表(您可能需要在方法中添加一些信息性异常):

/// <summary>
/// Represents a set of helpers for .net reflection
///  </summary>
public static class ReflectionHelper
{
    #region Public methods

    /// <summary>
    /// Gets a MethodInfo object from specified expression
    ///  </summary>
    /// <typeparam name="TResult"></typeparam>
    /// <param name="methodExpression"></param>
    /// <returns></returns>
    public static MethodInfo MethodOf<TResult>(Expression<Func<TResult>> methodExpression)
    {
        return ((MethodCallExpression)methodExpression.Body).Method;
    }

    /// <summary>
    /// Gets a MethodInfo object from specified expression
    ///  </summary>
    /// <param name="methodExpression"></param>
    /// <returns></returns>
    public static MethodInfo MethodOf(Expression<Action> methodExpression)
    {
        return ((MethodCallExpression)methodExpression.Body).Method;
    }

    /// <summary>
    /// Gets a MethodInfo object from specified expression
    ///  </summary>
    /// <param name="methodExpression"></param>
    /// <returns></returns>
    public static MethodInfo MethodOf<TInstance, TResult>(Expression<Func<TInstance, TResult>> methodExpression)
    {
        return ((MethodCallExpression)methodExpression.Body).Method;
    }

    /// <summary>
    /// Gets a MethodInfo object from specified expression
    ///  </summary>
    /// <param name="methodExpression"></param>
    /// <returns></returns>
    public static MethodInfo MethodOf<TInstance>(Expression<Action<TInstance>> methodExpression)
    {
        return ((MethodCallExpression)methodExpression.Body).Method;
    }

    /// <summary>
    /// Gets a PropertyInfo object from specified expression
    ///  </summary>
    /// <param name="propertyGetExpression"></param>
    /// <returns></returns>
    public static PropertyInfo PropertyOf<TProperty>(Expression<Func<TProperty>> propertyGetExpression)
    {
        return ((MemberExpression)propertyGetExpression.Body).Member as PropertyInfo;
    }

    /// <summary>
    /// Gets a PropertyInfo object from specified expression
    ///  </summary>
    /// <param name="propertyGetExpression"></param>
    /// <returns></returns>
    public static PropertyInfo PropertyOf<TInstance, TProperty>(Expression<Func<TInstance, TProperty>> propertyGetExpression)
    {
        return ((MemberExpression)propertyGetExpression.Body).Member as PropertyInfo;
    }

    /// <summary>
    /// Gets a FieldInfo object from specified expression
    ///  </summary>
    /// <param name="fieldAccessExpression"></param>
    /// <returns></returns>
    public static FieldInfo FieldsOf<TProperty>(Expression<Func<TProperty>> fieldAccessExpression)
    {
        return ((MemberExpression)fieldAccessExpression.Body).Member as FieldInfo;
    }

    //TODO: ConstructorOf(...)

    #endregion //Public methods
}

as I understand we could not use same aproach to getParameterInfo or EventInfo据我所知,我们不能使用相同的方法来获取参数信息或事件信息

Another approach to do that, described by Jb Evain, see: http://evain.net/blog/articles/2010/05/05/parameterof-propertyof-methodof?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+jbevain+%28Jb+in+a+nutshell%29另一种方法,由 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 +in+a+坚果壳%29

In c# 6 there's still no infoof but there is nameof :在 c# 6 中仍然没有infoof但有nameof

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

It's certainly not more terse, but at least it's refactoring friendly.它当然不是更简洁,但至少它是重构友好的。

Now in c#, we have nameof() .现在在 c# 中,我们有nameof()

Ref link参考链接

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM