将DataRow转换为继承DataRow的自定义类 [英] Cast DataRow To Custom Class That Inherits DataRow

查看:75
本文介绍了将DataRow转换为继承DataRow的自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天所有!!!



我有一个我正在循环的DataTable:



Good day all!!!

I have a DataTable that I'm looping through:

foreach (DataRow r in table.Rows)
{
}





我还有一个继承DataRow的类:





I also have a class that inherits DataRow:

public class OutlookDataRow : System.Data.DataRow
{
    public OutlookGridRow OutlookRow { get; set }

    public OutlookDataRow(System.Data.DataRowBuilder builder)
       : base(builder)
    {
    }
}





我如何将DataRow r转换为OutlookDataRow,因为它循环通过DataTable ???



执行任何后续抛出施法错误:





How would I go about casting DataRow r to OutlookDataRow as it loops through the DataTable???

Doing any of the follow throws a casting error:

OutlookDataRow dr = r;

OutlookDataRow dr = (OutlookDataRow)r;

OutlookDataRow dr = r as OutlookDataRow;

foreach (OutlookDataRow r in table.Rows)
{
}

推荐答案

你不能 - 你不能把继承作为系统投射up必须发明派生类中新项目的信息。因为它不知道你添加了什么或者你想用它做什么,它甚至都不会尝试。



最好的解决方案可能是定义派生类的构造函数,它将DataRow作为参数,并根据该信息构造新的OutlookDataRow。
You can't - you cannot cast "up" the inheritance tree as the system would have to "invent" information for new items in the derived class. Since it doesn't have a clue what you added or what you want to do with it, it won't even try.

The best solution is probably to define a constructor for your derived class which takes a DataRow as the parameter and constructs a new OutlookDataRow based on that information.


这篇关于将DataRow转换为继承DataRow的自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆