【发布时间】:2017-06-21 19:45:14
【问题描述】:
我想构建一个辅助方法,它将属性作为匿名方法的对象。这只是虚拟代码示例,用于可视化问题而不是面对更复杂的实际解决方案,并且不是这个问题的主题。
一些参考代码:
public class FooClass : SomeBaseClass {
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public DateTime DateTimeProperty { get; set; }
public Object ComplexObjectProperty { get; set; }
public FooClass() {
this.FooMethod(this.StringProperty);
this.FooMethod(this.IntProperty);
this.FooMethod(this.DateTimeProperty);
this.FooMethod(this.ComplexObjectProperty);
}
public void FooMethod<T>(T obj) {
Func<bool> validateMethod = () => {
if(obj is string) return string.IsNullOrEmpty(obj.ToString());
return obj != null;
};
this.ValidateMethodsAggregate.Add(validateMethod);
}
}
public class SomeBaseClass {
protected IList<Func<bool>> ValidateMethodsAggregate = new List<Func<bool>>();
public void ValidateAll() {
foreach (var validateMethod in this.ValidateMethodsAggregate) {
var result = validateMethod();
// has errors and so on handling...
}
}
}
// Some simple code to show use case.
var foo = new FooClass();
foo.StringProperty = "new value";
foo.IntProperty = 123;
foo.ValidateAll(); // this will use "" , 0 instead of new values.
【问题讨论】:
-
那么你为什么要在构造函数中调用你的验证方法呢?很明显,此时该属性还没有价值。为什么不在
StringProperty会被赋值的时候调用验证方法呢? -
您在构造函数中获得了
StringProperty的值,但您从未将其设置为任何值。当然,它将使用默认值。如果您想延迟读取该值,您可以更改FooMethiod()以接受PropertyInfo类型并在构造函数中使用反射来获取它,或者使用像FooMethod(() => StringProperty);这样的委托 -
你应该看看FluentValidation。
-
Delegate 或 PropertyInfo 就是答案。
-
@MatíasFidemraizer 我肯定会检查一下,但目前我在遗留框架中工作,该框架对验证过程中可以使用的内容有更多限制。干杯。
标签: c# .net validation properties anonymous-methods