如何从未经申报类型类和属性名和值 [英] 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; }
}
我可以使用一个通用的方法是这样的:
Can I use a generic method like this:
public void InitMethod(object classProperty)
要传递的数据是这样的:
To pass in data like this:
var a = new A() { Id = 1 };
var b = new B() { Name = "John" };
InitMethod(a.Id);
InitMethod(b.Name);
和从方法中获得以下信息:
And get the following information from within the method:
- 类名(例如:A,B)
- 属性名称(例如:ID,姓名)
- 属性值(例如:1,约翰)
推荐答案
排序的,尽管它可能是更多的麻烦比它的价值。
Sort of, although it may be more trouble than it is worth.
ASP.Net MVC经常使用前pressions获得在一个强类型的时尚属性信息。这位前pression不一定得到评估;相反,它被解析为它的元数据。
ASP.Net MVC frequently uses expressions to get at property info in a strongly-typed fashion. The expression doesn't necessarily get evaluated; instead, it is parsed for its metadata.
这是不特定于MVC;我提到它举在Microsoft框架中的既定模式。
This isn't specific to MVC; I mention it to cite an established pattern in a Microsoft framework.
下面是得到一个属性名称和值从EX pression一个例子:
Here's a sample that gets a property name and value from an expression:
// 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 );
}
您这样称呼它(注意传递的前pressions):
You call it like this (note the expressions being passed):
var foo = new Foo { Bar = "baz" };
string val = EvaluateProperty( o => foo.Bar );
foo = new Foo { Bar = "123456" };
val = EvaluateProperty( o => foo.Bar );
这篇关于如何从未经申报类型类和属性名和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!