开发者

Reference Private Property in Lambda expression?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜