2014-09-05 70 views
4

一个键,以便正常Dictionary<string, Action>我用像这样:Lambda表达式在字典

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给出名称的字符串表示。所以现在我必须弄清楚的是,如何填充字典!

+0

你可以使用'词典<对象,Action>' – Zer0 2014-09-05 07:46:49

+0

'x'应该是什么?你不能只使用'x.ThisProperty'? (没有lambda) – Sayse 2014-09-05 07:46:52

+2

呃,如果你根本不想错误输入字符串,为什么不使用'enum's? – 2014-09-05 07:47:35

回答

1

所以在看有关如何从拉姆达获取属性的名字,我用我的代码合并它@SriramSakthivel评论后,到目前为止,我得到了这是一个有效的解决方案:

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; 
}