【问题标题】:FastMember ObjectReader doesn't work with inherited interfacesFastMember ObjectReader 不适用于继承的接口
【发布时间】:2018-07-20 21:46:04
【问题描述】:

我从一个我无法控制的库中得到一个接口作为返回:

public interface IA : IB { String A { get;} }
public interface IB { String B { get;} }

现在当我尝试运行这段代码时,我得到了一个异常:

List<IA> list = library.Get();
IDataReader r = ObjectReader.Create(list, nameof(IA.A), nameof(IA.B));
while (r.Read())
{
    for (Int32 i = 0; i < r.FieldCount; i++)
    {
        //HERE ArgumentOutOfRangeException: Specified argument was out of the range of valid values.Parameter name: name
        Object o = r[i];
        Console.Write(o + ",");
    }
    Console.WriteLine();
}

它似乎找不到B 属性,因为它是在 IB 中声明的。我通过进行测试并直接在IA 中添加 B 来确认这一点。

我发现了一个非常糟糕的解决方法,它涉及创建一个实现 IA 的新类:

public class Ab : IA
{
    public Ab(String a, String b)
    {A = a;B=b;}

    public String A { get;}
    public String B { get;}
}

然后将List&lt;IA&gt; 转换为:List&lt;Ab&gt; newList = l.Select(e =&gt; new Ab(e.A, e.B).ToList(),然后是ObjectReader.Create(newList)。当我这样做时,ObjectReader 似乎找到了 B 属性。但这似乎非常浪费资源(和大量代码)来创建具有完全相同内容的中间对象。

是否有可能以不涉及创建新对象的另一种方式解决?

【问题讨论】:

  • 你总是可以打开一个问题?对我来说,这听起来像是一个普通的老错误。接口确实需要特别注意,因为在内部,它们的成员不会继承它们为类所做的方式,但我应该认为 FastMember 应该处理这个问题。

标签: c# fastmember


【解决方案1】:

我克隆了 FastMember 包的存储库,在 TypeAccessor 类中我将第 265 行从:

PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

到:

PropertyInfo[] props = GetPrpsInterfaces(type, BindingFlags.Public | BindingFlags.Instance).ToArray();

替换功能的实现:

static IEnumerable<PropertyInfo> GetPrpsInterfaces(Type type, BindingFlags flags)
{
      if (!type.IsInterface)
           return type.GetProperties(flags);

      return (new Type[] { type }).Concat(type.GetInterfaces()).SelectMany(i => i.GetProperties(flags));
}

我在这里找到: GetProperties() to return all properties for an interface inheritance hierarchy

这对我有用。

【讨论】:

  • 仅供参考 - 我用你的回答为快速会员创建了一个 PR。在 MemberSet.cs 的第 17 行还有一点需要更改的代码——这是同一种更改。你可以看看我的 PR github.com/mgravell/fast-member/pull/63/files
  • 感谢和抱歉迟到了,我希望您的请求将包含在下一个版本中。
猜你喜欢
  • 2017-02-22
  • 2019-03-14
  • 1970-01-01
  • 2010-11-30
  • 2015-09-11
  • 2017-01-24
  • 2016-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多