[英]Lambda Expression as a Key in dictionary
So a normal Dictionary<string, Action>
I use like so: 所以正常的
Dictionary<string, Action>
我这样使用:
validationsDictionary["ThisValidation"]();
However, strings can be missed typed. 但是,可以错过键入字符串。 So I would like to use the properties of a model as the key:
所以我想使用模型的属性作为关键:
validationsDictionary[x => x.ThisProperty]();
But, I don't know exactly what the type is going to be, I have tried these: 但是,我不知道具体是什么类型,我尝试过这些:
Dictionary<Func<Model>, Action>
Dictionary<Expressions<Model>, Action>
Dictionary<Expression<Func<Model>>, Action>
I know some people don't rate using functions as keys. 我知道有些人不会使用函数作为键。 So I could do something like this:
所以我可以这样做:
void Validate(Expression<Func<Model>> key)
{
validationsDictionary[key.ToString()]();
}
I don't know if key.ToString()
is a correct property to use, but you get the gist. 我不知道
key.ToString()
是否是一个正确的属性,但你得到了要点。
EDIT 编辑
So, I used this: 所以,我用过这个:
Expression<Func<DisplayContentViewModel, object>> predicate
And it works like a treat giving me the ability to do: x => x.SomeProperty
它就像一个让我有能力做的事情:
x => x.SomeProperty
I figured I can use predicate.Name
to give a string representation of the name. 我想我可以使用
predicate.Name
来给出名称的字符串表示。 So now all I have to figure out, is how to populate the dictionary! 所以现在我要弄清楚的是,如何填充字典!
So after looking at @SriramSakthivel comment about how to get property name from lambda, and I combined it with my code so far I got this as a working solution: 所以在看了@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.