【问题标题】:GetValue of PropertieInfo throws TargetParameterCountException (System.Reflection)PropertieInfo 的 GetValue 抛出 TargetParameterCountException (System.Reflection)
【发布时间】:2016-04-26 06:44:29
【问题描述】:

我已经在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# exception system.reflection propertyinfo getvalue


    【解决方案1】:

    问题是 Item 属性是索引的,即它有一个参数。 C# 通常不允许这样做,但其他 .NET 语言(例如 VB.NET)可以。因此,CLR 知道这个概念,反射也知道这个概念。在 C# 中,只有一种方法可以创建索引属性,即通过索引器。这在 CLR 级别的作用是创建一个名为 Item 的索引属性,因此您可能只是偶然发现了一个索引器。

    所以解决方法是检查属性信息是否有参数,如果有则继续for循环。您无法大致了解将哪些对象传递给索引属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 2012-11-29
      • 1970-01-01
      相关资源
      最近更新 更多