我想构建一个辅助方法,它将属性作为匿名方法的对象。这只是虚拟代码示例,可视化问题而不是面对真正的解决方案,这种解决方案更复杂,不受此问题的影响。
一些参考代码:
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.
答案 0 :(得分:0)
使用具有私有后备方法的函数和条件运算符
public FooClass()
{
this.FooMethod(() => StringProperty); // <- pass an accessor
}
public Func<bool> validateMethod;
private void FooMethod<T>(Func<T> obj)
{
//validate method
validateMethod = () => string.IsNullOrEmpty(obj()?.ToString());
}
用法是
var y = new FooClass();
var resTrue = y.validateMethod();
y.StringProperty = "Hi";
var resFalse = y.validateMethod();