jon*_*333 7 .net c# vb.net generics c#-2.0
我希望有人可以帮助我理解这样的事情是否可行.
在这种情况下,假设您尝试对电子表格或数据库中的网格进行建模,但每列中的数据只能是一种数据类型.
示例:第1列只能包含整数.
我创建了一个泛型类来模拟如下所示的列结构:
public class CollectionColumn<T>
{
private string _name;
private string _displayName;
private List<T> _dataItems = new List<T>();
public string Name {
get { return _name; }
set { _name = value; }
}
public string DisplayName {
get { return _displayName; }
set { _displayName = value; }
}
public List<T> Items {
get { return _dataItems; }
set { _dataItems = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想做的是拥有一个容器用于各种列(可能有CollectionColumn,CollectionColumn等)和它自己的属性,但我不知道如何做到这一点,我仍然可以访问列和数据当我不知道他们的类型时,在他们内
这是一个.NET 2.0项目,所以像动态这样的东西不起作用,也许是一个对象列表?我也不确定是否有办法用接口来做到这一点.
public class ColumnCollection
{
public int Id { get; set; }
public string ContainerName { get; set; }
private List<CollectionColumn<T>> _columns;
public List<CollectionColumn<T>> Columns {
get { return _columns; }
set { _columns = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是将各种CollectionColumn添加到ColumnCollection的Columns集合中,这样我就可以拥有包含各种类型数据的列.
任何帮助将非常感谢.
Ada*_*son 10
这是一个相当普遍的问题.您需要做的是声明泛型类继承的非泛型基类或泛型类实现的非泛型接口.然后,您可以创建该类型的集合.
例如,
public abstract class CollectionColumnBase
{
private string _name;
private string _displayName;
public string Name {
get { return _name; }
set { _name = value; }
}
public string DisplayName {
get { return _displayName; }
set { _displayName = value; }
}
public abstract object GetItemAt(int index);
}
public class CollectionColumn<T> : CollectionColumnBase
{
private List<T> data = new List<T>();
public overrides object GetItemAt(int index)
{
return data[index];
}
public List<T> Items
{
get { return data; }
set { data = value; }
}
}
public class ColumnCollection
{
public int Id { get; set; }
public string ContainerName { get; set; }
private List<CollectionColumnBase> _columns;
public List<CollectionColumnBase> Columns {
get { return _columns; }
set { _columns = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1487 次 |
| 最近记录: |