Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用refection获取所有属性并在方法中传递每个属性_C#_Wpf_Inotifydataerrorinfo - Fatal编程技术网

C# 使用refection获取所有属性并在方法中传递每个属性

C# 使用refection获取所有属性并在方法中传递每个属性,c#,wpf,inotifydataerrorinfo,C#,Wpf,Inotifydataerrorinfo,我正在使用simplemvvmtoolkit进行验证(INotifyDataErrorInfo)。我不想对视图模型中的每个属性一遍又一遍地重复我自己,我想使用反射来获取所有属性并验证它们,但我似乎不知道在validateProperty方法中传递什么 private void ValidateInput() { var unitProperties = this.GetType().GetProperties()

我正在使用simplemvvmtoolkit进行验证(INotifyDataErrorInfo)。我不想对视图模型中的每个属性一遍又一遍地重复我自己,我想使用反射来获取所有属性并验证它们,但我似乎不知道在validateProperty方法中传递什么

    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包含:

    protected virtual void ValidateProperty<TResult>(Expression<Func<TViewModel, TResult>> property, object value);
受保护的虚拟void ValidateProperty(表达式属性、对象值);

问题是
表达式
属性信息
(由
GetProperties
返回的类型)绝对没有关系。您还将遇到问题,因为编译时不知道结果的类型

最简单的解决方案是更改
ValidateProperty
以接受
PropertyInfo

protected virtual void ValidateProperty(PropertyInfo property, object value);
您还可以将
属性info
转换为
表达式
,但这有点困难:

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) });
}

感谢您的响应,更改ValidateProperty以接收PropertyInfo需要对方法的工作方式进行实现更改,对吗?此方法是simpleMvvmToolkit中的元数据的一部分。@TMan它肯定需要修改此方法。这些变化的剧烈程度取决于现在的实施方式以及其他可用设施。大多数情况下,asp.net MVC中的表达式参数只是作为一种更符合语法要求(且类型安全)的方式来将PropertyInfo传递到方法中,因此我怀疑可能已经有一种方法可以满足您对PropertyInfo的需要。如果您已经实现了INotifyDataErrorInfo,您就不能调用GetErrors(名称)吗每个属性名称的方法?