继承时缺少方法异常

时间:2013-01-15 14:30:30

标签: c# datatable

我有以下继承自DataTable的类:

public class ExcelStaticDataTable : DataTable
{
    public List<ExcelStaticDataTable> SubTables { get; set; }
    public ExcelStaticDataTable(string tableName): base(tableName)
    {
        SubTables = new List<ExcelStaticDataTable>();
    }
}

你知道为什么我为这个对象定义MissingMethodException“无参数构造函数”当我执行以下操作时:

ExcelStaticDataTable table=new ExcelStaticDataTable("table1");
table.Clone();

这两段代码都在不同的dll中,只是为了澄清。这里是stacktrace:

at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Data.DataTable.CreateInstance()
   at System.Data.DataTable.Clone(DataSet cloneDS)
   at System.Data.DataTable.Clone()
   at System.Data.DataTable.Copy()
   at ..........cs:line 35

感谢。

1 个答案:

答案 0 :(得分:5)

我怀疑其他代码正在使用object newObj = Activator.CreateInstance(GetType());作为Clone()的一部分。这需要默认用法中的公共无参数构造函数。否则会抛出MissingMethodException

更新:显示堆栈跟踪的更新确认了这一点。

我怀疑你可以通过覆盖CreateInstance方法来解决这个问题:

protected override DataTable CreateInstance()
{
    return new ExcelStaticDataTable(TableName);
}