我想要做的是采用任何类类型并为对象图中的所有属性创建一个'get'访问器列表。以编程方式创建属性访问器函数的集合
集合的确切格式,顺序等并不重要,我只是不知道如何开始识别和创建所有属性的访问器。这可能需要的东西的形式是这样的:
public static List<Func<T,object>> CreateAccessors<T>()
{
Type t = typeof(T);
// Identify all properties and properties of properties (etc.) of T
// Return list of lambda functions to access each one given an instance of T
}
public void MyTest()
{
MyClass object1;
var accessors = CreateAccessors<MyClass>();
var myVal1 = accessors[0](object1);
var myVal2 = accessors[1](object1);
// myVal1 might now contain the value of object1.Property1
// myVal2 might now contain the value of object1.Property4.ThirdValue.Alpha
}
看看Jon Skeet的这篇博文 - https://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx,它很漂亮除了递归之外,所有这些都很重要。 – 2012-01-27 16:57:32
你可能也想看到这个http://stackoverflow.com/questions/16578857/using-nested-collections-of-lambda-expressions-to-create-an-object-graph – nawfal 2013-06-02 15:46:01
乔恩的MVP博客不见了,这是一个他的(个人?)博客上的帖子副本: https://codeblog.jonskeet.uk/2008/08/09/making-reflection-fly-and-exploring-delegates/ – 2016-04-14 21:49:31