关于继承和投射

时间:2016-02-28 17:07:08

标签: c# inheritance casting datatable

我正面临一个问题,我无法弄清楚如何管理。

我开发了一个在DataTable上实现非唯一索引的类;为了处理商品,我正在考虑开发我的IndexedTable,显然,它继承自DataTable,添加了一种使用非唯一索引在表上执行搜索的方法

我写道:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DWH_Core
{
    class IndexedTable : DataTable
    {
        //private  DataTable m_tbl;
        //public Dictionary<Int32, Int32> idx;

        private Index_NonUnique m_idx = null;
        public void buildNonUniqueIndex(string keyField)
        {
            m_idx = new Index_NonUnique();
            m_idx.buildIndex(this, keyField);

            return;
        }

        public DataRow[] search (string key)
        {
            return m_idx.search(key);
        }

        public DataRow[] search(int key)
        {
            return m_idx.search(key);
        }

        public DataRow[] search(short key)
        {
            return m_idx.search(key);
        }

    }
}

及相关课程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DWH_Core
{
    class Index_NonUnique
    {
        private string m_KeyField;
        private ILookup<object, DataRow> m_IdxByKey;

        public void buildIndex(DataTable tbl, string keyField)
        {
            m_KeyField = keyField;

            IEnumerable<DataRow> enumerable = tbl.AsEnumerable();
            m_IdxByKey = enumerable.ToLookup(o => o[keyField]);
        }


        public DataRow[] search(string keyValue)
        {
            return m_IdxByKey[keyValue].ToArray();
        }

        public DataRow[] search(int keyValue)
        {
            return m_IdxByKey[keyValue].ToArray();
        }

        public DataRow[] search(short keyValue)
        {
            return m_IdxByKey[keyValue].ToArray();
        }
    }
}

问题在于,当我以通常的方式生成DataTable类,并尝试将其转换为IndexedTable时,我得到了运行时错误&#34;无法从类型&#39; System的对象执行转换.Data.DataTable&#39;在类型&#39; DWH_Core.IndexedTable&#39;。&#34;。 我不想使用private DataTable m_tbl成员,因为我想将所有DataTable成员应用于我的IndexedTable对象,但我无法理解如何管理此错误。 最后,我的目标是写下这样的东西:

 IndexedTable tmpTable = null;
 SqlCommand cmd = "SELECT * FROM SOME_TABLE"
 SqlDataReader rdr = cmd.ExecuteReader();

 m_SAP_Allocazione = (IndexedTable)rdr.ToTable();
 m_SAP_Allocazione.buildNonUniqueIndex("PERNR");

1 个答案:

答案 0 :(得分:1)

以下是关于将对象转换为派生类的一些答案。

https://docs.python.org/2/library/subprocess.html

Is it possible to assign a base class object to a derived class reference with an explicit typecast in C#?

答案是否定的,这是不可能的。

  

执行此操作的最简单方法是执行您的建议:创建DerivedClass(BaseClass)构造函数