无法强制转换类型为';的对象;系统Int32';键入';系统反射RuntimePropertyInfo

本文关键字:系统 对象 Int32 键入 RuntimePropertyInfo 反射 类型 转换 | 更新日期: 2023-09-27 18:00:33

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

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

我已经为每个属性制作了一个如何进行转换的类,如下所示:

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

源属性总是字符串,并且数据在前一步中经过验证,所以我知道我可以毫无例外地进行强制转换。因此,对于每个属性,我都有一个转换规则。有些转换是纯转换,而另一些则在表中进行查找。

在上面的例子中,我有一个列描述列表,如下所示:

 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。无法强制转换类型为"System"的对象。Int32"到类型"System。反射从TransformationClass返回时的RuntimePropertyInfo。

也许我对这个问题的处理方式完全错误。任何意见都将不胜感激。

无法强制转换类型为';的对象;系统Int32';键入';系统反射RuntimePropertyInfo

这一行就是问题所在:

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

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

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