美文网首页
c#6.0nameof和4.0自定义方法使用

c#6.0nameof和4.0自定义方法使用

作者: 好怕怕 | 来源:发表于2019-10-30 19:35 被阅读0次

    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;
    }
    

    相关文章

      网友评论

          本文标题:c#6.0nameof和4.0自定义方法使用

          本文链接:https://www.haomeiwen.com/subject/bzomyctx.html