0
我想構建一個幫助方法,它將屬性作爲匿名方法的對象。這只是一個虛擬代碼示例,用於將問題可視化,而不是面對真正的解決方案,這種解決方案更爲複雜,並且不屬於此問題的主題將屬性作爲對象傳遞給方法
一些參考代碼:
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)的委託。 ' – itsme86
你應該看看[FluentValidation](https://github.com/JeremySkinner/FluentValidation)。 –