PropertieInfo 的 GetValue 抛出 TargetParameterCountException (System.Reflection)

GetValue of PropertieInfo throws TargetParameterCountException (System.Reflection)

我已经在 SharePoint 部分错误地发布了这个问题。

我需要将一个模型映射到另一个模型。一切正常,但最后一个 属性 抛出 TargetParameterCountException。抛出异常的属性叫"Item"这个属性不是我定义的,我假设这是字典里的属性

我已经尝试使用所有五个参数,而不是只使用一个(如此处所述 Moq + Unit Testing - System.Reflection.TargetParameterCountException: Parameter count mismatch),但不幸的是我会遇到同样的异常。如果有人能帮助我,我将不胜感激。

金德问候和感谢

桑德罗

这是源模型的摘录,所有其他属性都以完全相同的方式实现:

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

问题是项目 属性 已编入索引,即它有一个参数。 C# 通常不允许这样做,但是 VB.NET 等其他 .NET 语言允许这样做。因此,这个概念为 CLR 所知,因此也为 Reflection 所知。在 C# 中,只有一种方法可以创建索引 属性,即通过索引器。这在 CLR 级别所做的是创建一个名为 Item 的索引 属性,因此您可能刚刚偶然发现了一个索引器。

所以解决办法是检查属性信息是否有参数,如果有则继续for循环。您没有机会大致了解要将哪些对象传递到索引 属性.