我想为 LoadFromXML 加载和验证创建一个通用的辅助方法。如果我从中加载的 XML 不完整,我确实希望它完全失败而不抛出异常。目前,我的代码看起来像这样(或多或少)
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
使用的私有(private)成员变量.这是我针对此问题的当前解决方案,但我面临一个主要问题:因为我无法将属性本身传递给 LoadHelper
和 Action<string>
与属性不匹配 :(,我现在正在规避属性 setter 逻辑。
为了你自己的想法,在 LoadHelper
之前抽象,我的每一个List<Func<XElement, bool>>
的条目看起来像这样......
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)),
问题:有谁知道在不绕过属性的 setter 逻辑的情况下执行此操作的方法吗?
最佳答案
Action doesn't match the property
如果我没看错,您尝试用“Action<string>
”替换“ref string index”,然后尝试传递 Protperty。接近但不完全是。怎么样?
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),
关于c# - 将属性作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3587580/