【发布时间】:2009-08-19 13:13:17
【问题描述】:
编辑:我更改了措辞,添加了长示例代码以更具描述性
我需要通过 BindingSource 读取对象绑定的类型名称。
我的方法接受 BindingSource 作为参数,它不知道 BindingSource '托管'的对象类型。但我需要阅读那个对象类型
为了更好地解释我的意思,假设我有 2 个类
class Person {
public string Name { get; set; }
public List<Parent> Parents { get; set; }
}
class Parent {
public string Name { get; set; }
public int ChildrenCount { get; set; }
}
比我在 Windows 窗体绑定场景中使用它们:
// Create Person List
List<Person> Persons = new List<Person>();
// add Sample data
Persons.Add(new Person() { Name = "Person_1" });
Persons.Add(new Person() { Name = "Person_2" });
Persons[0].Parents = new List<Parent>();
Persons[0].Parents.Add(new Parent() { Name = "Father_1", ChildrenCount = 2 });
Persons[0].Parents.Add(new Parent() { Name = "Mother_1", ChildrenCount = 2 });
Persons[1].Parents = new List<Parent>();
Persons[1].Parents.Add(new Parent() { Name = "Father_2", ChildrenCount = 1 });
Persons[1].Parents.Add(new Parent() { Name = "Mother_2", ChildrenCount = 1 });
// create binding sources
BindingSource bs1 = new BindingSource(Persons, null);
BindingSource bs2 = new BindingSource(bs1, "Parents");
// bind to grid
dataGridView1.DataSource = bs1;
dataGridView2.DataSource = bs2;
// ****************************************
// ****** Read type 'hosted' by BS ********
// ****************************************
// BS1 - Expected: System.Collections.Generic.List`1[Person]
// That's easy...
Console.WriteLine("type bind to BS1=" + bs1.DataSource.GetType());
// BS2 - Expected: System.Collections.Generic.List`1[Person]
// HOW TO READ THAT ??!!
// this returns BindingSource type
Console.WriteLine("type bind to BS2=" + bs2.DataSource.GetType());
// this returns: System.Collections.Generic.List`1[Person] (I need List<Parents> or Person.List<Parents>"
Console.WriteLine("type bind to BS2=" + (bs2.DataSource as BindingSource).DataSource.GetType());
所以,正如您所注意到的,这是主从绑定(bs1 绑定到一个网格,bs2 绑定到第二个网格)*
所以我想通过 bindingSource bs2 以某种方式读取“托管”类型(预期类型是 List )
我需要写的方法如下:
Type GetBSType (BindingSource bs)
感谢任何帮助...
【问题讨论】:
-
您能否更好地阐明您的意图?该代码似乎试图实现未描述的内容,我们也许可以为您提供的示例提供另一种方法。
-
@Yoooder - 同意...示例是菊花链绑定源。从描述中,我希望:
bs2.DataSource = new List<Parent>();
标签: c# .net reflection binding