繁体   English   中英

如何从未声明的类型中获取类和属性名称和值

[英]How to get class and property names and values from undeclared type

如果我有这两个类:

public class A
{
    public int Id { get; set; }
}

public class B
{
    public string Name { get; set; }
}

我可以使用这样的通用方法:

public void InitMethod(object classProperty)

要传递这样的数据:

var a = new A() { Id = 1 };
var b = new B() { Name = "John" };

InitMethod(a.Id);
InitMethod(b.Name);

并从方法中获取以下信息:

  • 班级名称(例如:“A”,“B”)
  • 属性名称(例如:“Id”,“名称”)
  • 财产价值(例如:1,“约翰”)

虽然它可能比它的价值更麻烦但有点排序。

ASP.Net MVC经常使用表达式以强类型方式获取属性信息。 表达式不一定得到评估; 相反,它被解析为其元数据。

这不是MVC特有的; 我提到它引用Microsoft框架中的既定模式。

这是从表达式获取属性名称和值的示例:

// the type being evaluated
public class Foo
{
    public string Bar {
        get;
        set;
    }
}

// method in an evaluator class
public TProperty EvaluateProperty<TProperty>( Expression<Func<Foo, TProperty>> expression ) {
    string propertyToGetName = ( (MemberExpression)expression.Body ).Member.Name;

    // do something with the property name

    // and/or evaluate the expression and get the value of the property
    return expression.Compile()( null );
}

你这样称呼它(注意传递的表达式):

var foo = new Foo { Bar = "baz" };
string val = EvaluateProperty( o => foo.Bar );

foo = new Foo { Bar = "123456" };
val = EvaluateProperty( o => foo.Bar );

在这个例子中,你需要将对象传递给InitMethod而不是该对象的属性,也许它会没问题。

class Program
{
    static void Main(string[] args)
    {
        InitMethod(new A() { Id = 100 });
        InitMethod(new B() { Name = "Test Name" });

        Console.ReadLine();
    }

    public static void InitMethod(object obj)
    {
        if (obj != null)
        {
            Console.WriteLine("Class {0}", obj.GetType().Name);
            foreach (var p in obj.GetType().GetProperties())
            {
                Console.WriteLine("Property {0} type {1} value {2}", p.Name, p.GetValue(obj, null).GetType().Name, p.GetValue(obj, null));
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM