![](/img/trans.png)
[英]Force derived class to implement base class constructor with parameter(s)
[英]Force class derived from abstract class to implement constructor
我有一个自定义异常,如下所示:
public abstract class MyException : Exception
{
public MyException()
{
}
public MyException(string message) : base(message)
{
}
public MyException(string message, Exception inner) : base(message, inner)
{
}
public abstract HttpStatusCode GetHttpStatusCode();
}
派生类:
public class ForbiddenException : MyException
{
public override HttpStatusCode GetHttpStatusCode()
{
return HttpStatusCode.Forbidden;
}
}
我希望派生类要么使用,要么被迫实现抽象类中的构造函数格式。
目前使用上面的内容,当我尝试创建ForbiddenException
,我收到以下错误:
throw new ForbiddenException("Request forbidden");
ForbiddenException does not contain a constructor that takes 1 arguments
我可以手动将构造函数放入MyException
每个派生类中,但这很容易出错并重复自己。
任何意见,将不胜感激。
如果要在重写时避免复制和粘贴/错误,请考虑使用文本模板。 我把它放在我的玩具类库中的.tt
模板中,我还将你的MyException
复制到:
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
using System;
namespace ClassLibrary2
{
<# StandardConstructors("public","ForbiddenException","MyException"); #>
}
<#+
public void StandardConstructors(string modifiers,
string derivedException, string baseException)
{
Write(modifiers);
Write(" partial class ");
Write(derivedException);
Write(":");
WriteLine(baseException);
WriteLine("{");
Write("\tpublic ");
Write(derivedException);
WriteLine("() {}");
Write("\tpublic ");
Write(derivedException);
WriteLine("(string message):base(message)");
WriteLine("\t{}");
Write("\tpublic ");
Write(derivedException);
WriteLine("(string message, Exception inner):base(message,inner)");
WriteLine("\t{}");
WriteLine("}");
}
#>
我立即得到的唯一错误是我没有实现GetHttpStatusCode
但我希望你在一个单独的文件中编写它,该文件也定义了相同的部分ForbiddenException
类。 每个新派生的异常只需要您将另一个StandardConstructors
行添加到模板文件中。 更不容易出错。
当然,你可以随心所欲地做到这一点,我只是在几分钟内从头开始写这个1 。
这是以上模板产生的一个:
using System;
namespace ClassLibrary2
{
public partial class ForbiddenException:MyException
{
public ForbiddenException() {}
public ForbiddenException(string message):base(message)
{}
public ForbiddenException(string message, Exception inner):base(message,inner)
{}
}
}
不漂亮,但它不一定是 - 它是生成的代码。
1例如,如果标签/间距确实让您感到烦恼,那么例如您是否希望更多地控制修饰符等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.