簡體   English   中英

無法將類型為“ 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; }
}

我制作了一類關於如何對每個屬性進行轉換的類,如下所示:

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

在運行時獲取實例。從TransformationClass返回時,無法將類型為“ System.Int32”的對象轉換為類型為“ System.Reflection.RuntimePropertyInfo”。

也許我以一種完全錯誤的方式來解決這個問題。 任何輸入將不勝感激。

這行是問題所在:

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

您在toProp上調用GetType() -這將返回派生自PropertyInfo某種類型。 實際上需要屬性類型,因此只需將其更改為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM