代码之家  ›  专栏  ›  技术社区  ›  Enriquev

从类中获取对象类型

  •  1
  • Enriquev  · 技术社区  · 15 年前

    我怎么能做到这一点?:

    public class myClass
    {
     public string first;
     public int second;
     public string third;
    }
    
    public string tester(object param)
    {
     //Catch the name of what was passed not the value and return it
    }
    
    //So:
    myClass mC = new myClass();
    
    mC.first = "ok";
    mC.second = 12;
    mC.third = "ko";
    
    //then would return its type from definition :
    tester(mC.first) // would return : "mc.first" or "myClass.first" or "first"
    //and 
    tester(mC.second) // would return : "mc.second" or "myClass.second" or "second"
    
    3 回复  |  直到 15 年前
        1
  •  9
  •   Marc Gravell    15 年前

    在没有 infoof 你能做的最好的就是 Tester(() => mC.first) 通过表达式树…

    using System;
    using System.Linq.Expressions;
    public static class Test
    {
        static void Main()
        {
            //So:
            myClass mC = new myClass();
    
            mC.first = "ok";
            mC.second = 12;
            mC.third = "ko";
            //then would return its type from definition :
            Tester(() => mC.first); // writes "mC.first = ok"
            //and 
            Tester(() => mC.second); // writes "mC.second = 12"
        }
        static string GetName(Expression expr)
        {
            if (expr.NodeType == ExpressionType.MemberAccess)
            {
                var me = (MemberExpression)expr;
                string name = me.Member.Name, subExpr = GetName(me.Expression);
                return string.IsNullOrEmpty(subExpr)
                    ? name : (subExpr + "." + name);
            }
            return "";
        }
        public static void Tester<TValue>(
            Expression<Func<TValue>> selector)
        {
            TValue value = selector.Compile()();
    
            string name = GetName(selector.Body);
    
            Console.WriteLine(name + " = " + value);
        }
    }
    
        2
  •  0
  •   Thomas Levesque    15 年前

    这是不可能的。编译的代码中不存在变量名,因此无法在运行时检索变量名。

        3
  •  0
  •   Philippe Leybaert    15 年前

    那是不可能的。”param“将没有关于值来自何处的信息。

    调用tester()时,会复制某个属性中的值,因此该属性的“链接”将丢失。