本文介绍了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

推荐答案

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 13:53