检查对象是否与给定列表中的任何类型匹配的替代方法

if (this.Page is ArticlePage|| this.Page is ArticleListPage) { //Do something fantastic } 

上面的代码是有效的,但考虑到可能有很多不同的类,我想比较this.Page to,我想将类存储在列表中,然后在列表上执行.Contains()

我怎么做到这一点? 我会以某种方式使用GetType()吗? 我可以存储一个Page对象列表,然后以某种方式比较这些类型吗?

注意:您可以假设我正在比较this.Page所有类以扩展Page

这段代码可以完成这项工作:

 HashSet knownTypes = new HashSet() { typeof(ArticlePage), typeof(ArticleListPage), // ... etc. }; if (knownTypes.Contains(this.Page.GetType()) { //Do something fantastic } 

编辑:正如Chris指出的那样,您可能需要考虑类型inheritance来完全模仿is运算符的行为。 这有点慢,但对某些目的更有用:

 Type[] knownTypes = new Type[] { typeof(ArticlePage), typeof(ArticleListPage), // ... etc. }; var pageType = this.Page.GetType(); if (knownTypes.Any(x => x.IsAssignableFrom(pageType))) { //Do something fantastic } 

很难评论您的确切用法,但是(相对)简单的方法来执行此操作并为您的检查添加更多的整洁( 特别是如果您在多个位置执行相同的检查)是定义一个接口,让相关的页面实现那个界面,然后对此进行检查。

空接口:

 public interface IDoSomethingFantastic { } 

例如,您的两个页面定义可能如下所示:

 public partial class ArticlePage : System.Web.UI.Page, IDoSomethingFantastic { } public partial class ArticleListPage : System.Web.UI.Page, IDoSomethingFantastic { } 

那你的支票基本上是:

 if (this.Page is IDoSomethingFantastic) { //Do something fantastic } 

这样做的好处是不必集中存储“精彩”页面列表; 相反,您只需在页面类声明中定义它,就可以轻松添加/删除“精彩”页面。

此外,您可以将“奇妙”的行为移动到界面/页面:

 public interface IDoSomethingFantastic { void SomethingFantastic(); } 

然后在你的检查代码中:

 if (this.Page is IDoSomethingFantastic) { ((IDoSomethingFantastic)this.Page).SomethingFantastic(); } 

通过这种方式,可以在其他地方处理奇妙的实现,而不是重复。 或者您可以将检查和操作完全移到单独的处理类中:

 if (FantasticHandler.IsPageFantastic(this.Page)) FantasticHandler.DoSomethingFantastic(this.Page); 

虽然你应该重新考虑使用这样的代码(因为它似乎忘记了多态),你可以使用Reflection来检查它:

 List types = new List() { typeof(ArticlePage), typeof(ArticleListPage) }; types.Any(type => type.IsAssignableFrom(@object.GetType())); 

IsAssignableFrom不仅适用于特定类,也适用于所有子类,非常类似于运算符。