中的服务(,我不能改变)我有两个对象类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
)到两个独立的ListViews。我需要每个人都有一个额外的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合起来了吗?任何我没有想到的事情?
你可能想看看这个https://en.wikipedia.org/wiki/Adapter_pattern – BlackBear
您无法修改该文件或无法修改该文件屁股?例如,你可以实现一个部分类。但是,你将不得不将原来的类改为部分类。 –
@ScottNimrod我无法修改服务中的任何类或文件,例如'Bar','Baz'和'Type'类。如果我愿意,我会很乐意让前两个从基类或接口继承 - 这会让我在有限的经验中简化事情变得更容易。 – OhBeWise