6.0
using System;
namespace NameofUsage
{
/// <summary>
/// C# nameof用法
/// </summary>
internal class Program
{
private static void Main()
{
Console.Title = "C# nameof用法";
Person p = new Person();
Console.WriteLine(nameof(p));
Console.WriteLine(nameof(p.Name));
Console.WriteLine(nameof(Person.CreateDateTime));
Console.ReadKey();
}
}
public class Person
{
public long Id { get; set; }
public string Name { get; set; }
public DateTime CreateDateTime { get; set; }
}
}
image.png
4.0
方法一:
public static class MemberInfoGetting
{
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
}
string TableName = "123";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => TableName);
//最后得到 nameOfTestVariable = "TableName"
方法二:
static void Main(string[] args)
{
GetName(new { var1 });
GetName2(() => var1);
GetName3(() => var1);
}
static string GetName<T>(T item) where T : class
{
return typeof(T).GetProperties()[0].Name;
}
static string GetName2<T>(Expression<Func<T>> expr)
{
return ((MemberExpression)expr.Body).Member.Name;
}
static string GetName3<T>(Func<T> expr)
{
return expr.Target.GetType().Module.ResolveField(BitConverter.ToInt32(expr.Method.GetMethodBody().GetILAsByteArray(), 2)).Name;
}
网友评论