在一个我无法更改的服务中,我有两个对象类
在一个WPF屏幕中,我正在将每种类型(Baz和Bar)的列表绑定到两个单独的ListView上。我需要每个都有一个额外的选中复选框列。为此,我创建了一个包装类,其中包含公共属性、额外的Selected属性和每个的构造函数:
为了将每个类别为
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属性和每个的构造函数:
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;
}
问题:
如何将这个设计泛化?
理论、实现和错误:
Since the constructors are virtually the same besides the
Bar
andBaz
parameters, can I somehow use generic typeT
to make one constructor and still grab the properties?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); ... } ... }
Change the constructors to receive the whole collection of
Qux
objects and do thequxs.Single(qux => qux.ID == object.ObjectQux)
logic there. Then make the extension methods into one generic method, something like the following.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; }
Both 1 and 2 combined? Anything I haven't thought of?
Bar
、Baz
和Type
类。如果我可以的话,我想让前两个继承基类或接口——这将使我在泛化事物方面的经验受益更多。 - OhBeWise