将属性作为参数传递 [英] Passing properties as parameters
问题描述
我想为LoadFromXML加载和验证创建一个通用的帮助器方法.如果我要加载的XML不完整,我希望它完全失败而不会引发异常.目前,我的代码看起来(或多或少)
I want to create a generalized helper method for LoadFromXML loading and validation. If the XML I'm loading from is incomplete, I do want it to fail completely without throwing an exception. Currently, my code looks like this (more or less)
public override bool Load(XElement source)
{
return new List<Func<XElement, bool>>
{
i => this.LoadHelper(i.Element(User.XML_Username), ref this._username, User.Failure_Username),
i => this.LoadHelper(i.Element(User.XML_Password), ref this._password, User.Failure_Password)
//there are many more invokations of LoadHelper to justify this architecture
}
.AsParallel()
.All(i => i.Invoke(source));
}
private bool LoadHelper(XElement k, ref string index, string failure)
{
if (k != null && k.Value != failure)
{
index = k.Value;
return true;
}
return false;
}
this._username
是属性this.Username
使用的私有成员变量.这是针对此问题的当前解决方案,但是我面临一个主要问题:由于我无法将属性本身传递给LoadHelper
,并且Action<string>
与该属性不匹配:(,我正在规避属性设置器逻辑.
this._username
is a private member variable that is used by the property this.Username
. This is the current solution I have for this problem, but I'm facing one major issue: Since I cannot pass the property itself to the LoadHelper
and Action<string>
doesn't match the property :(, I'm circumventing the property setter logic right now.
出于自己的考虑,在LoadHelper
抽象之前,我的List<Func<XElement, bool>>
的每个条目都像这样...
For your own musings, before the LoadHelper
abstraction, each of my List<Func<XElement, bool>>
's entries looked like this...
i => ((Func<XElement, bool>)(k => { if (k == null || k.Value == User.Failure_Username) return false;
{ this.Username = k.Value; return true; } })).Invoke(i.Element(User.XML_Username)),
问题:在不回避该属性的设置者逻辑的情况下,有人知道这样做吗?
Question: Does anyone know any way to do this without circumventing the property's setter logic?
推荐答案
操作与属性不匹配
Action doesn't match the property
如果我没看错,您尝试用"Action<string>
"替换引用字符串索引",然后尝试传递属性.接近但不完全是.怎么样?
If I read that right, you tried replacing the "ref string index", with "Action<string>
" and then tried passing the Protperty. Close but not quite. How 'bout?
private bool LoadHelper(XElement k, Action<string> setter, string failure)
{
if (k != null && k.Value != failure)
{
setter(k.Value);
return true;
}
return false;
}
然后
i => this.LoadHelper(i.Element(User.XML_Username), s=>{this.Username = s},
User.Failure_Username),
这篇关于将属性作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!