C#在低于6.0版本实现nameof
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
namespace ConsoleApp
{
class Program
{
class People
{
public int ID { get; set; }
public List<string> ListArr { get; set; }
}
static void Main(string[] args)
{
string s = "取代nameof";
People people = new People();
Console.WriteLine("---NameOf<T>(T t)---");
Console.WriteLine(NameOf(new { people }));
Console.WriteLine(NameOf(new { s }));
Console.WriteLine(NameOf(new { people.ID }));
Console.WriteLine(NameOf(new { people.ListArr }));
Console.WriteLine();
Console.WriteLine("---Expression<Func<T>>---");
Console.WriteLine(NameOf(() => people));
Console.WriteLine(NameOf(() => s));
Console.WriteLine(NameOf(() => people.ID));
Console.WriteLine(NameOf(() => people.ListArr));
Console.ReadKey();
}
/// <summary>
/// 利用匿名类型实现 参数t必须为匿名类型
/// </summary>
public static string NameOf<T>(T t) where T : class
{
return typeof(T).GetProperties().Select(s => s.Name).FirstOrDefault();
}
/// <summary>
/// 利用lambda实现
/// </summary>
public static string NameOf<T>(Expression<Func<T>> expr)
{
return ((MemberExpression)expr.Body).Member.Name;
}
}
}
输出: