[英]How do I retrieve a reference to a subobject using Reflection in C#?
[英]How do I build this c# “Expression” at runtime using reflection?
直到今天,我還沒有找到一篇關於表達的好文章 - 以及如何查看C#lambda語句並說“哦,那是一個等等等等......”所以,如果你知道一篇好文章,我會很感激這也是一個答案。
所以...給出以下c#代碼:
public class SomeClass<T>
{
public TResult SomeMethod<TResult>(Expression<Func<T, TResult>> expression)
{
// This is just an example... don't get hung up on this :)
return default(TResult);
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
我該怎么做呢...
var blah = new SomeClass<Person>();
blah.SomeMethod(p => p.FirstName);
在運行時(使用反射)?
我有點期待這樣的事情...但我確信我選擇的表達方式已經過時了。
// By the way, these values are being passed to me... so you
// can't change this part of the question :)
Type personType = typeof(Person);
string propertyName = "FirstName";
// THIS CODE BELOW IS OBVIOUSLY WRONG, BUT YOU GET THE IDEA OF
// WHAT I HOPE TO DO... THIS LINE OF CODE BELOW IS **ALL** I'M
// ASKING HOW TO DO :)
var expression = Expression.MakeUnary(ExpressionType.Lambda,
Expression.Property(Expression.Parameter(personType, "p"),
propertyName), typeof(string));
blah.SomeMethod(expression);
試試這個:
var functorParam = Expression.Parameter(typeof(Person));
var lambda = Expression.Lambda(
Expression.Property(functorParam, typeof(Person).GetProperty("FirstName"))
, functorParam /* <<= EDIT #1 */
);
blah.SomeMethod((Expression<Func<Person,string>>)lambda); /* EDIT #2 */
ExpressionBuilder是要走的路。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.