通用集合多态类型作为参数

时间:2016-05-09 15:42:07

标签: c# generics data-binding casting

考虑以下结构

class A {}
class B : A {}
class C : A {}
class D : A {}
...

// in data source class
BindingList<B> d1;
BindingList<C> d2;
BindingList<D> d3;
...

// in datagridview class
void BindDataSource(BindingList<A> source);
void QueryDataSource() {
  BindingList<A> source = (BindingList<A>)dgv.DataSource;
  A a = source.First(...);
}

我希望将d1d2 ...绑定到DataGridViewBindDataSource sot,以便对d1和{进行任何更改{1}}会自动反映在d2中。从this post我了解到上述代码无效。但该帖子中没有一个解决方案适用于我的情况。我尝试将DataGridView更改为以下

BindDataSource

但现在void BindingDataSource<T>(BindingList<T> source) where T:A; 无法编译,因为我无法转换DataSource。有没有办法解决整个事情?

1 个答案:

答案 0 :(得分:1)

一些选择。

选项1:让d1 ... d3为function compile() { const input = document.getElementById("input"); const transpiled = document.getElementById("transpiled"); const output = document.getElementById("output"); transpiled.value = Opal.compile(input.value); output.value = eval(transpiled.value); } document.onload = function() { compile(); } 个实例,但只插入B,C,     D进入他们。

选项2:拥有一个集合,并查询/过滤     需要时B,C和D.

选项3:做这样的事情。

BindingList<A>

选项4:使用通用方法。

BindDataSource(
    new BindingList<A>(d1.ToList<A>())
)
相关问题