Nameof()替代.NET [英] Nameof() alternative for .NET

查看:64
本文介绍了Nameof()替代.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Reflection编写NameOf的替代方法。我使用VS 2010并且NameOf不可用。我需要在结构的层次结构中获取任何类型的任何成员的名称。



How would you code an alternative to NameOf using Reflection. I am using VS 2010 and NameOf is not available. I need to get the names of any Members of any Type in the hierarchy of the Structure.

Structure Market
    Public Vehicle As Vehicle
    Public Place As String
End Structure

Structure Vehicle
    Public [Color] As Color
   
End Structure

Usage:
Dim Market As String = NameOf(GetType(Market)) ' "Market"
Dim Vehicle As String = NameOf(GetType(New Market().Vehicle)) '"Vehicle" or "Market.Vehicle"
Dim Place As String = NameOf(GetType(New Market().Place)) '"Place" or "Market.Place"





我尝试过:





What I have tried:

Function NameOf(Of T)(ByVal expression As T) As String

End Function

推荐答案

反射将无效,因为在您的示例中,每次调用 GetType 将返回 System.String ,或者该变量的类型。你不会在 Type 类的任何实例上找到你的变量名。



它可以是使用表达式树完成,但执行起来很昂贵。在任何需要每秒执行数千次的情况下使用此代码,您会注意到性能损失。

Reflection won't work because, in your example, every call to GetType is going to return System.String, or whatever the type of the variable is. You're not going to find your variable name on any instance of the Type class.

It can be done using an Expression Tree, but this its expensive to execute. Use this code in any case where you have to execute it thousands of times a second and you're going to notice quite the performance hit.
class Program
{
    static void Main(string[] args)
    {
        string Market = string.Empty;

        Console.WriteLine(Ext.GetNameOf(() => Market));
    }

}

public static class Ext
{
    public static string GetNameOf<T>(Expression<Func<T>> expression)
    {
        var body = (MemberExpression)expression.Body;

        return body.Member.Name;
    }
}


这篇关于Nameof()替代.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆