【问题标题】:Adding methods to converter class with an interface使用接口向转换器类添加方法
【发布时间】:2017-01-13 11:57:58
【问题描述】:

我编写了一个相当简单的转换类,它将Foo 转换为Bar

因为我想要其他类的多个转换器,所以我设置了两个方法的接口:

public interface IConverter<in TSource, out TDestination>
{
    TDestination Convert(TSource sourceObject);
    IEnumerable<TDestination> ConvertMany(IEnumerable<TSource> sourceObjects);
}

我的班级是这样实现的:

public class ObjectConverter : IConverter<Foo, Bar>
{
    public Bar Convert(Foo sourceObject)
    {
        return new Bar
        {
            // Mapping attributes...
        };
    }
    public IEnumerable<Bar> ConvertMany(IEnumerable<Foo> sourceObjects)
    {
        return sourceObjects.Select(obj => new Bar
            {
                // Mapping attributes...
            });
    }        
}

这一切都很棒。我想添加另一个ConvertMany 方法,它将另一个对象作为源并将其返回为Bar。是否可以将其添加到此类,因为它还返回 Bar,或者这是否更适合同样实现此接口的第二个类?

我对 C# 和使用接口还很陌生,所以我不确定什么会更好。

(顺便说一句,这是否有意义?有更好的选择吗?)

【问题讨论】:

  • 您只想为其他源对象添加一个其他方法还是至少添加两个已实现的方法?
  • 两者都可以,但我只需要ConvertMany
  • 所以你应该像这样使用它:ObjectConverter : IConverter&lt;Foo, Bar&gt;, IConverter&lt;Baz, Bar&gt;
  • 您可能想阅读内置 TypeConverter 上的文档,您可以从中继承您自己的类。
  • @Jamiec 我肯定会经历这个,但这基本上只是为了提高可读性。感觉不需要复杂的代码。

标签: c# interface converter


【解决方案1】:

您应该添加另一个接口实现以实现预期结果:

public interface IConvertFromMany<TSource, TDestination>
{
    IEnumerable<TDestination> ConvertMany(IEnumerable<TSource> sourceObjects);
}

public interface IConverter<TSource, TDestination> : IConvertFromMany<TSource, TDestination>
{
    TDestination Convert(TSource sourceObject);

}

像这样使用它:

public class ObjectConverter : IConverter<Foo, Bar>, IConvertFromMany<AnotherSourceObject, Bar>
{
   //....your implementations here        
}

【讨论】:

  • 我知道这有什么意义,但是如果我只想拥有ConvertMany 方法怎么办,如果我只是将它添加到该类中会被认为是不好的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-09-23
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
  • 2017-08-19
  • 1970-01-01
  • 2013-10-04
相关资源
最近更新 更多