简体   繁体   English

分配不同类型的对象

[英]Assigning objects of different type

I am new to VB.Net and I'm a little confused why this line happened to be valid in VB: 我是VB.Net的新手,我有点困惑为什么这行在VB中有效:

DataGridView1.DataSource = ds.Tables("Customerslist")

DataSource is of type Object while Tables("Customerslist") is of type DataTable. DataSource是Object类型,而Tables(“ Customerslist”)是DataTable类型。 How will I know what types of objects can be assigned to the Datasource property? 我将如何知道可以将哪些类型的对象分配给Datasource属性?

DataTable derives from Object , so can be assigned to any Object variable. DataTable源自Object ,因此可以分配给任何Object变量。

From MSDN ( DataSource ): 从MSDN( DataSource ):

The DataGridView class supports the standard Windows Forms data-binding model. DataGridView类支持标准Windows窗体数据绑定模型。 This means the data source can be of any type that implements one of the following interfaces: 这意味着数据源可以是实现以下接口之一的任何类型:

  • The IList interface, including one-dimensional arrays. IList接口,包括一维数组。
  • The IListSource interface, such as the DataTable and DataSet classes. IListSource接口,例如DataTable和DataSet类。
  • The IBindingList interface, such as the BindingList class. IBindingList接口,例如BindingList类。
  • The IBindingListView interface, such as the BindingSource class. IBindingListView接口,例如BindingSource类。

In .NET all classes are ultimately derived from object so field/property of type object can be used to store a reference to anything. 在.NET中,所有类最终都是从object派生的,因此可以使用类型为object字段/属性存储对任何内容的引用。

This can be useful when you need to store a reference to something that might be one of a number of potentially related types. 当您需要存储对可能是许多潜在相关类型之一的内容的引用时,这很有用。 It does mean though that when you come to use that reference you need to check what type it really is. 这确实意味着,当您开始使用该引用时,您需要检查它的真正类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM