相关疑难解决方法(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万
查看次数

是否可以将属性名称作为字符串传入并为其赋值?

我正在设置一个简单的帮助器类来保存我正在解析的文件中的一些数据.属性的名称与我期望在文件中找到的值的名称相匹配.我想添加一个调用AddPropertyValue到我的类的方法,这样我就可以为属性赋值而无需通过名称显式调用它.

该方法如下所示:

//C#
public void AddPropertyValue(string propertyName, string propertyValue) {
   //code to assign the property value based on propertyName
}

---

'VB.NET'
Public Sub AddPropertyValue(ByVal propertyName As String, _
                            ByVal propertyValue As String)
    'code to assign the property value based on propertyName '
End Sub
Run Code Online (Sandbox Code Playgroud)

实现可能如下所示:

C#/ VB.NET

MyHelperClass.AddPropertyValue("LocationID","5")
Run Code Online (Sandbox Code Playgroud)

这是否可能无需针对提供的每个单独的属性名称进行测试propertyName

.net c# vb.net reflection

6
推荐指数
1
解决办法
4859
查看次数

标签 统计

c# ×2

.net ×1

expression-trees ×1

lambda ×1

linq ×1

reflection ×1

vb.net ×1