Is it possible to reference a private property in a lambda expression? Or only public properties?
For example. say my private property is named InnerCollection, the line of code would be:
x => x.InnerCollection
Is there a way 开发者_Python百科to achieve this somehow - without using reflection etc.?
Using .NET 4.0.
Thanks.
Chris
No, unless (unlikely) the lambda is defined inside a method of the class of x
.
You can use this outside or inside of the class, This is only working for fields right now but you can modify it for properties if you want.
public static Func<T, R> GetFieldAccessor<T, R>(string fieldName)
{
ParameterExpression param =
Expression.Parameter(typeof(T), "arg");
MemberExpression member =
Expression.Field(param, fieldName);
LambdaExpression lambda =
Expression.Lambda(typeof(Func<T, R>), member, param);
Func<T, R> compiled = (Func<T, R>)lambda.Compile();
return compiled;
}
usage would looks something like this:
public class MyClass
{
private int _secret = 10;
}
var myClass = new MyClass();
Console.WriteLine("func:" + GetFieldAccessor<MyClass, int>("_secret").Invoke(myClass));
Unless the lambda definition is in a method of the class the private field/property is defined in, no there isn't. You'll have to deal with reflection then.
精彩评论