リフレクションを使用してモデル プロパティをループし、プロパティを en 式として期待するメソッドに渡したいと考えています。
たとえば、次のモデルがあるとします。
public class UserModel
{
public string Name { get; set; }
}
そして、このバリデータークラス:
public class UserValidator : ValidatorBase<UserModel>
{
public UserValidator()
{
this.RuleFor(m => m.Username);
}
}
そして私の ValidatorBase クラス:
public class ValidatorBase<T>
{
public ValidatorBase()
{
foreach (PropertyInfo property in
this.GetType().BaseType
.GetGenericArguments()[0]
.GetProperties(BindingFlags.Public | BindingFlags.Insance))
{
this.RuleFor(m => property); //This line is incorrect!!
}
}
public void RuleFor<TProperty>(Expression<Func<T, TProperty>> expression)
{
//Do some stuff here
}
}
問題はValidatorBase()
コンストラクターにあります-必要なプロパティがある場合、コンストラクターの行と同じように機能するように、メソッドのパラメーターPropertyInfo
として何を渡す必要がありますか?expression
RuleFor
UserValidator()
または、これを機能させるために他の何かを使用する必要がありPropertyInfo
ますか?