开发者

asp.net convert anonymous function parameter to string

H开发者_开发技巧ow can I get this anonymous function to return "object.Property" as a string?

() => object.Property;

Thanks!


Edit following clarification of requirements:

var foo = GetYourObjectFromSomewhere();
string bar = ExprToString(() => foo.Property);    // bar = "foo.Property"

// ...

public static string ExprToString<T>(Expression<Func<T>> e)
{
    // use a stack and a loop so that we can cope with nested properties
    // for example, "() => foo.First.Second.Third.Fourth.Property" etc

    Stack<string> stack = new Stack<string>();

    MemberExpression me = e.Body as MemberExpression;
    while (me != null)
    {
        stack.Push(me.Member.Name);

        me = me.Expression as MemberExpression;
    }

    return string.Join(".", stack.ToArray());
}

Original answer:

It's not entirely clear what you need, or what the type of object.Property is in the first place. Maybe one of the following would do the trick?

// either
() => (string)object.Property

// or
() => object.Property.ToString()


Based on your additional explanation and requirements, you can solve this by asking for an Expression<Func<T, TProperty>> instaed of a Func<T, TProperty>.

You could implement this something like this:

public string GetPropertyName<T, TProperty>(Expression<Func<T, TProperty>> propertyPicker)
{
     MemberExpression me = (MemberExpression)propertyPicker.Body;
     return me.Member.Name;
}

This would allow you to call it like this:

string name = GetPropertyName(x => x.Property);

since there exists an implicit conversion from Func<T, TResult> to Expression<Func<T, TResult>>.

A more complete explanation, as well as a reusable API can be found on Kzu's blog.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜