如何使用附加属性和方法扩展 C# 中的 DataRow 和 DataTable?
我想创建一个自定义 DataRow,它有一个名为 IsCheapest 的属性。
public class RateDataRow : DataRow
{
protected internal RateDataRow(DataRowBuilder builder) : base(builder)
{
}
public bool IsCheapest { get; set ;}
}
我想要一个仅包含 ***RateDataRow*** 的新 DataTable,以便 .NewDataRow() 将 RateDataRow 实例作为新行返回。
扩展 DataTable 的类的实现应该是什么?
谢谢,
I would like create a custom DataRow that will have -let's say- a propery called IsCheapest.
public class RateDataRow : DataRow
{
protected internal RateDataRow(DataRowBuilder builder) : base(builder)
{
}
public bool IsCheapest { get; set ;}
}
And I want to have a new DataTable that contains only ***RateDataRow***s so that .NewDataRow() returns RateDataRow instance as a new row.
what should be the implementation on the class that extends DataTable?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我知道这是一篇旧文章,但我无法使上面的示例发挥作用。我遇到了类似的问题,所以很想找到解决方案。经过一番研究后,我发现以下方法有效:
I know this is an old post now but I couldn't get the example above to work. I had a similar problem so was keen to find a solution. After a bit of research I found the following to work:
DataTable 公开 GetRowType 虚拟方法,在派生类中重写该方法。任何尝试添加错误类型的行都会引发异常:
The DataTable exposes a GetRowType virtual method, override this in a derived class. Any attempts to add a row of the wrong type will throw an exception:
从您的问题来看,尚不清楚您是否熟悉类型化数据集。它们基本上就是您所要求的。
您可以使用内置向导创建基于 XSD 的类型化数据集(XSD 是从 Db 架构中提取的)。在 WinForms 项目中,选择“添加数据源”并按照以下步骤操作。
即使您不想使用该模型,您也可以从属性、部分类等的代码中借用。
明智的做法是使用该模型或保持非常接近它。
From your question it's not clear if you are familiar with Typed Datasets. They basically are what you are asking for.
You could use the built-in wizards to create a Typed Dataset based on an XSD (and the XSD is extracted from the Db schema). In a WinForms project, select "Add DataSource" and follow the steps.
Even if you don't want to use that model you could borrow from the code for properties, partial classes etc.
It would be wise to either use that model or stay very close to it.