相关疑难解决方法(0)

从lambda表达式中检索属性名称

通过lambda表达式传入时,是否有更好的方法来获取属性名称?这是我现在拥有的.

例如.

GetSortingInfo<User>(u => u.UserId);
Run Code Online (Sandbox Code Playgroud)

只有当属性是字符串时,它才能将其作为元素表达式进行处理.因为不是所有属性都是字符串我必须使用对象,但它会返回一个单一表达式.

public static RouteValueDictionary GetInfo<T>(this HtmlHelper html, 
    Expression<Func<T, object>> action) where T : class
{
    var expression = GetMemberInfo(action);
    string name = expression.Member.Name;

    return GetInfo(html, name);
}

private static MemberExpression GetMemberInfo(Expression method)
{
    LambdaExpression lambda = method as LambdaExpression;
    if (lambda == null)
        throw new ArgumentNullException("method");

    MemberExpression memberExpr = null;

    if (lambda.Body.NodeType == ExpressionType.Convert)
    {
        memberExpr = 
            ((UnaryExpression)lambda.Body).Operand as MemberExpression;
    }
    else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
    {
        memberExpr = lambda.Body as MemberExpression;
    }

    if (memberExpr …
Run Code Online (Sandbox Code Playgroud)

c# linq lambda expression-trees

489
推荐指数
14
解决办法
21万
查看次数

获取属性的名称作为字符串

(参见下面我使用我接受的答案创建的解决方案)

我正在尝试提高一些涉及反射的代码的可维护性.该应用程序有一个.NET Remoting接口,公开(除此之外)一个名为Execute的方法,用于访问未包含在其已发布的远程接口中的应用程序部分.

以下是应用程序如何指定可通过Execute访问的属性(本例中为静态属性):

RemoteMgr.ExposeProperty("SomeSecret", typeof(SomeClass), "SomeProperty");
Run Code Online (Sandbox Code Playgroud)

所以远程用户可以调用:

string response = remoteObject.Execute("SomeSecret");
Run Code Online (Sandbox Code Playgroud)

并且应用程序将使用反射来查找SomeClass.SomeProperty并将其值作为字符串返回.

不幸的是,如果有人重命名SomeProperty并忘记更改ExposeProperty()的第3个parm,它会破坏这种机制.

我需要相当于:

SomeClass.SomeProperty.GetTheNameOfThisPropertyAsAString()
Run Code Online (Sandbox Code Playgroud)

在ExposeProperty中用作第三个parm,因此重构工具将负责重命名.

有没有办法做到这一点?提前致谢.

好的,这是我最终创建的内容(根据我选择的答案和他引用的问题):

// <summary>
// Get the name of a static or instance property from a property access lambda.
// </summary>
// <typeparam name="T">Type of the property</typeparam>
// <param name="propertyLambda">lambda expression of the form: '() => Class.Property' or '() => object.Property'</param>
// <returns>The name of the property</returns>
public string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
    var me = propertyLambda.Body as MemberExpression;

    if (me == null)
    { …
Run Code Online (Sandbox Code Playgroud)

c# reflection properties

191
推荐指数
9
解决办法
20万
查看次数

标签 统计

c# ×2

expression-trees ×1

lambda ×1

linq ×1

properties ×1

reflection ×1