質問

I'm using simplemvvmtoolkit for validation (INotifyDataErrorInfo). Instead of me repeating my self over and over for each property within the view model, Id like to use reflection to get all the properties and validate them, I can't seem to figure out what to pass in the validateProperty method though.

    private void ValidateInput()
    {
        var unitProperties = this.GetType().GetProperties()
                                   .Where(x => x.CanRead);

        foreach (var prop in unitProperties)
            ValidateProperty(prop, prop.GetValue(this, null)); //????
                   //? ^ get errors here 


    }

ValidateProperty takes in:

    protected virtual void ValidateProperty<TResult>(Expression<Func<TViewModel, TResult>> property, object value);
役に立ちましたか?

解決

The problem is Expression<Func<TViewModel, TResult>> has absolutely no relation to PropertyInfo (the type returned by GetProperties). You'll also run into problems because the type of the result is not known at compile time.

The easiest solution would be to change ValidateProperty to accept a PropertyInfo:

protected virtual void ValidateProperty(PropertyInfo property, object value);

You could also convert the PropertyInfo to an Expression, but that's a bit more difficult:

var method = this.GetType().GetMethod("ValidateProperty");
foreach (var prop in unitProperties)
{
    var parameter = Expression.Parameter(this.GetType(), "_");
    var property = Expression.Property(parameter, prop);
    var lambda = Expression.Lambda(property, parameter);
    var genericMethod = method.MakeGenericMethod(prop.PropertyType);
    genericMethod.Invoke(this, new object[] { lambda, prop.GetValue(this, null) });
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top