的类型没有构造定义
问题描述:
我想继承一个容器类,它是一个又一个DLL的一部分,它具有以下结构的类型没有构造定义
namespace MySdk
{
// Summary:
// Container class used to encapsulate individual mark details
public class MathsReport: IEnumerable
{
// Summary:
// A list of mark details.
public List<Mark> Marks;
// Summary:
// Get access to the C# IEnumerator interface of the mark reports list.
//
// Returns:
// The IEnumerator interface to the list of mark reports.
public IEnumerator GetEnumerator();
}
}
我的代码
public class MyReport : MathsReport
{
}
它抛出The type MySdk.MathsReport has no constructors defined
。
为什么它抛出错误,并限制我从inherting。我该如何克服它?
答
为了重申评论中所说的话,MathsReport
没有公共的构造函数,这意味着你不能有效地继承它。
但是,您可以添加扩展方法来执行各种“额外”的事情,而无需实际继承该类。显然,这与实际的继承不同,但对您的用例来说可能已经足够了。扩展类的
例子:
public static class MathsReportExtensions
{
public static Mark GetBestMark(this MathsReport mathsReport)
{
//this is just a sample code which returns the first Mark from the collection
return mathsReport.First();
}
}
用法:
using NamespaceToExtensionClass;
//...
public void SomeMethodUsingMathsReport(MathsReport mathsReport)
{
var bestMark = mathsReport.GetBestMark();
}
你给出的代码就可以了,但据推测'MathsReport' * *实际上声明了一个构造函数,但内部/私人访问。您的子类需要访问该构造函数才能链接到它。您是否能够查看和/或更改其他DLL中的代码? –
为'MathsReport'显示的代码看起来与反编译的版本非常相似,您应该检查它是否有构造函数,如果它确实(我确信它确实),构造函数具有哪个访问修饰符。 –
@JonSkeet谢谢,正如@Lasse V. Karlsen所说,它是一个反编译的代码,上面的代码就是我在DLL中看到的。 MathsReport类没有其他代码 –