Lambda表达式作为字典中的键

时间:2014-09-05 07:45:10

标签: c# dictionary lambda

所以正常Dictionary<string, Action>我这样使用:

validationsDictionary["ThisValidation"]();

但是,可以错过键入字符串。所以我想使用模型的属性作为关键:

validationsDictionary[x => x.ThisProperty]();

但是,我并不确切知道这种类型是什么,我尝试过这些:

Dictionary<Func<Model>, Action>
Dictionary<Expressions<Model>, Action>
Dictionary<Expression<Func<Model>>, Action>

我知道有些人不会使用功能作为键。所以我可以这样做:

void Validate(Expression<Func<Model>> key) 
{
    validationsDictionary[key.ToString()]();
}

我不知道key.ToString()是否是一个正确的属性,但你得到了要点。

修改

所以,我用过这个:

Expression<Func<DisplayContentViewModel, object>> predicate

它的作用就像让我能够做到的一种享受:x => x.SomeProperty

我想我可以使用predicate.Name来提供名称的字符串表示。所以我现在要弄清楚的是,如何填充字典!

1 个答案:

答案 0 :(得分:1)

所以在看了@SriramSakthivel关于如何从lambda获取属性名称的评论之后,我将它与我的代码结合到目前为止我将其作为一个有效的解决方案:

private void Validate(Expression<Func<DisplayContentViewModel, object>> propertyLambda)
{
    var key = this.GetValidationKey(propertyLambda);

    this.validationsDictionary[key]();
}

private void CreateValidationRule(
    Expression<Func<DisplayContentViewModel, object>> propertyLambda,
    Action validationAction)
{
    if (this.validationsDictionary == null)
    {
        this.validationsDictionary = new Dictionary<string, Action>();
    }

    var key = this.GetValidationKey(propertyLambda);

    if (this.validationsDictionary.ContainsKey(key))
    {
        return;
    }

    this.validationsDictionary.Add(key, validationAction);
}

private string GetValidationKey(Expression<Func<DisplayContentViewModel, object>> propertyLambda)
{
    var member = propertyLambda.Body as UnaryExpression;

    if (member == null)
    {
        throw new ArgumentException(
            string.Format("Expression '{0}' can't be cast to a UnaryExpression.", propertyLambda));
    }

    var operand = member.Operand as MemberExpression;

    if (operand == null)
    {
        throw new ArgumentException(
            string.Format("Expression '{0}' can't be cast to an Operand.", propertyLambda));
    }

    return operand.Member.Name;
}