无法将类型 'System.Int32' 的对象转换为类型 'System.Reflection.RuntimePropertyInfo'

Unable to cast object of type 'System.Int32' to type 'System.Reflection.RuntimePropertyInfo'

我有几个要转换的实体。这是一个例子:

 public class FromClass
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public string TimeStamp { get; set; }
}

public class ToClass
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int TypeId { get; set; }
    public DateTime TimeStamp { get; set; }
}

我已经 class 说明了如何为每个 属性 完成转换,如下所示:

  public interface ITransformationRule
    {
        T Transform<T>(string value);
    }
    public class ColumnDescription
    {
        public string SourceColumnName { get; set; }
        public string TargetObjectProperty { get; set; }
        public ITransformationRule TransformationRule { get; set; }
    }

源属性始终是字符串,并且数据在上一步中经过验证,因此我知道我可以毫无例外地进行转换。所以对于每个 属性 我都有一个转换规则。一些转换是普通转换,而其他转换在表中进行查找。

在上面的例子中,我有一个像这样的 ColumnDescriptions 列表:

 public List<ColumnDescription> TransformationDescription = new List<ColumnDescription>
    {
        new ColumnDescription{SourceColumnName = "Id", TargetObjectProperty = "Id", TransformationRule = new IntegerTransformation() }

    };

等等...现在我迷路了(或者 ITransformationRule 界面应该看起来有点不同)。我这样写 IntegerTransformationClass:

  public class IntegerTransformation : ITransformationRule
    {
        public T Transform<T>(string value)
        {
            object returnvalue = int.Parse(value);
            return (T) returnvalue;
        }
    }

最后我像这样遍历列表中的属性:

foreach (var row in TransformationDescription)
        {
            ¨...
            var classType = row.TransformationRule.GetType();
            var methodInfo = classType.GetMethod("Transform");
            var generic = methodInfo.MakeGenericMethod(toProp.GetType());
            var parameters = new object[] { toProp.ToString() };
            var toValue = generic.Invoke(specialTransform.TransformationRule, parameters);
            toProp.SetValue(toObj, Convert.ChangeType(toValue, toProp.PropertyType), null);
        }

在运行时获取 exeption.Unable 以在从 TransformationClass 返回时将类型 'System.Int32' 的对象转换为类型 'System.Reflection.RuntimePropertyInfo'。

也许我以完全错误的方式解决了这个问题。如有任何意见,我们将不胜感激。

这一行是问题所在:

var generic = methodInfo.MakeGenericMethod(toProp.GetType());

您在 toProp 上调用 GetType() - 这将 return 从 PropertyInfo 派生的某种类型。您 实际上 想要 属性 类型,所以只需将其更改为:

var generic = methodInfo.MakeGenericMethod(toProp.PropertyType);