c# – 当类有错误的继承时如何抛出异常
发布时间:2020-12-15 08:44:45 所属栏目:百科 来源:网络整理
导读:我有一个asp.net webforms应用程序.每个aspx.cs类都需要从继承自System.Web.UI.Page的BasePage.cs继承. 所需页面继承: class MyChildPage : BasePage : System.Web.UI.Page 如何在创建新子页面时强制它从BasePage.cs而不是System.Web.UI.Page继承? 潜在解
我有一个asp.net webforms应用程序.每个aspx.cs类都需要从继承自System.Web.UI.Page的BasePage.cs继承.
所需页面继承: class MyChildPage : BasePage : System.Web.UI.Page 如何在创建新子页面时强制它从BasePage.cs而不是System.Web.UI.Page继承? 潜在解决方案 >有没有办法更改aspx.cs页面的默认创建? 注意:这些子页面共享相同的母版页,这可能会有所帮助. 解决方法
您可以使用验证所有页面的自定义MSBuild任务来实现此功能.例如,这是一个Task,它将检查只有BasePage继承自Page.如果任何其他类继承自Page,则会在输出中记录错误,并且构建将失败:
public class CheckBasePage : Task { public override bool Execute() { var assm = Assembly.LoadFile("/path/to/WebsiteAssembly.dll"); var types = assm.GetTypes(); var pages = new List<string>(); foreach (var t in types) { if (t.BaseType == typeof(Page) && t.Name != "BasePage") { pages.Add(t.FullName); } } if (pages.Count > 0) { Log.LogError("The following pages need to inherit from BasePage: [" + string.Join(",",pages) + "]"); return false; } return true; } } 然后,您将在项目文件中将此自定义任务添加为构建过程的一部分: <UsingTask TaskName="CheckBasePage" AssemblyFile="/path/to/MyCustomTasksAssembly.dll" /> <Target Name="PostBuild"> <CheckBasePage /> </Target> 现在假设MyCustomTasksAssembly是您为管理这样的自定义MSBuild任务而创建的单独项目.如果要将CheckBasePage任务嵌入到与其余代码相同的项目中,则需要应用same trick from here. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |