【发布时间】:2015-09-24 18:11:39
【问题描述】:
在一项服务(我无法更改)中,我有两个对象类 Bar 和 Baz,它们的属性大多相似(但遗憾的是,不,它们不是从相同的基类或从相同的接口继承...是的——愚蠢),以及与它们的相对BarQux 和BazQux 属性相关的依赖类:
public class Bar public class Baz
{ {
public int ID { get; set; } public int ID { get; set; }
public bool Active { get; set; } public bool Active { get; set; }
public int BarQux { get; set; } public int BazQux { get; set; }
... ...
} }
public class Qux
{
public int ID { get; set; } // Corresponds to BarQux and BazQux
public string Name { get; set; }
}
在 WPF 屏幕中,我将每种类型的列表(Baz 和 Bar)绑定到两个单独的 ListView。我需要每个人都有一个额外的Selected CheckBox 列。为此,我创建了一个包含公共属性的包装类、附加的Selected 属性以及每个属性的构造函数:
public class Foo
{
public Foo(Bar bar, Qux qux)
{
this.Active = bar.Active;
this.FooQux = string.Format("{0} - {1}", qux.ID, qux.Name);
...
}
public Foo(Baz baz, Qux qux)
{
this.Active = baz.Active;
this.FooQux = string.Format("{0} - {1}", qux.ID, qux.Name);
...
}
public bool Selected { get; set; }
public int ID { get; set; }
public bool Active { get; set; }
public string FooQux { get; set; }
...
}
为了将 Baz 和 Bar 类的每个集合转换为 Foo 的集合,我创建了以下扩展方法:
public static List<Foo> ToFoo(this IEnumerable<Bar> bars, IEnumerable<Qux> quxs)
{
List<Foo> foos = new List<Foo>();
foreach (Bar bar in bars)
{
Foo foo = new Foo(bar, quxs.Single(qux => qux.ID == bar.BarQux));
foos.Add(foo);
}
return foos;
}
public static List<Foo> ToFoo(this IEnumerable<Baz> bazs, IEnumerable<Qux> quxs)
{
List<Foo> foos = new List<Foo>();
foreach (Baz baz in bazs)
{
Foo foo = new Foo(baz, quxs.Single(qux => qux.ID == baz.BazQux));
foos.Add(foo);
}
return foos;
}
问题:
如何使这个通用化?
理论、实施和错误:
-
由于除了
Bar和Baz参数之外,构造函数几乎相同,我可以以某种方式使用泛型类型T创建一个构造函数并仍然获取属性吗?public class Foo<T> { public Foo(T obj, Qux qux) { this.Active = obj.Active; // 'T' does not contain a definition for 'Active'... this.Qux = string.Format("{0} - {1}", qux.ID, qux.Name); ... } ... } -
更改构造函数以接收
Qux对象的整个集合并在那里执行quxs.Single(qux => qux.ID == object.ObjectQux)逻辑。然后将扩展方法变成一个泛型方法,如下所示。public static List<Foo> ToFoo<T>(this IEnumerable<T> objCollection, IEnumerable<Qux> quxs) { List<Foo> foos = new List<Foo>(); foreach (T obj in objCollection) { Foo foo = new Foo(obj, quxs); // The best overloaded method... has some invalid arguments. foos.Add(foo); } return foos; } 1 和 2 合并?有什么我没有想到的吗?
【问题讨论】:
-
不能修改文件还是不能修改类?例如,您可以实现部分类。但是,您必须将原始类更改为部分类。
-
@ScottNimrod 我无法修改服务中的任何类或文件,例如
Bar、Baz和Type类。如果可以的话,我想让前两个继承自基类或接口 - 这将使我在概括事物方面的有限经验更容易。 -
这看起来像是一个 DTO 对象到/从 BusinessObject 的案例。您可以完全控制 businessObject 实现,但 DTO 对象实际上来自“难以”更改的外部服务。