簡體   English   中英

PropertieInfo的GetValue拋出TargetParameterCountException(System.Reflection)

[英]GetValue of PropertieInfo throws TargetParameterCountException (System.Reflection)

我錯誤地在SharePoint部分發布了這個問題。

我需要將一個模型映射到另一個模型。 一切正常,但最后一個屬性拋出TargetParameterCountException。 拋出異常的屬性稱為“Item”,此屬性不是由我定義的,我假設這是字典中的屬性。

我已經嘗試使用所有五個參數而不是僅使用一個(如此處所述Moq +單元測試 - System.Reflection.TargetParameterCountException:參數計數不匹配 )但不幸的是我會得到相同的異常。 如果有人可以幫助我,我將非常感激。

金德問候並謝謝

桑德羅

這是源模型的摘錄,所有其他屬性以完全相同的方式實現:

public class DataModel : Dictionary<string, object> {}
public class DiscussionDataModel : DataModel
{
  public DiscussionDataModel(Dictionary dictionary) : base(dictionary){}

  public FieldUserValue Author
  {
    get { return (FieldUserValue) this["Author"]; }
    set { this["Author"] = value; }
  }

  public double AverageRating
  {
    get { return (double) this["AverageRating"]; }
    set { this["AverageRating"] = value; }
  }
}

這是目標模型的摘錄,所有其他屬性以完全相同的方式實現:

public class DiscussionModel : BaseModel
{
  public FieldUserValue Author { get; set; }
  public double AverageRating { get; set; }
}

這是將DataModel映射到BaseModel的通用擴展方法:

public static T ToModel(this DataModel dataModel) where T : BaseModel
{
  try
  {
    T model = Activator.CreateInstance();
    if (dataModel != null)
    {
      PropertyInfo[] propertyInfos = dataModel.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

      foreach (PropertyInfo propertyInfo in propertyInfos)
      {
        object value = propertyInfo.GetValue(dataModel);
        if (value == null) { break; }
        PropertyInfo modelPropertyInfo = model.GetType().GetProperty(propertyInfo.Name);
        modelPropertyInfo?.SetValue(model, value);
      }
      return model;
    }
  }
  catch (Exception ex)
  {
    throw;
  }
  return null;
}

問題是Item屬性是索引的,即它有一個參數。 C#通常不允許這樣做,但其他.NET語言如VB.NET也是如此。 因此,這個概念對於CLR是已知的,因此對於反射也是已知的。 在C#中,只有一種方法可以創建索引屬性,即通過索引器。 這在CLR級別的作用是創建一個名為Item的索引屬性,因此您可能只是偶然發現了一個索引器。

所以解決方案是檢查屬性信息是否有參數,如果是這種情況則繼續for循環。 您通常不會知道要傳遞給索引屬性的對象。

暫無
暫無

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

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