An alternative way to check if an object matches any type in this list

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

The code above works, but given the fact that there can be many different classes that I would like to compare with this.Page, I would like to keep the classes in a list and then execute .Contains()in a list.

How can i achieve this? Am I using it GetType()somehow? Can I save a list of objects Pageand somehow compare their types?

Note. You can read all the classes I'm comparing this.Pagefor extension Page.

+4
source share
3 answers

This code will complete the task:

HashSet<Type> knownTypes = new HashSet<Type>()
{
    typeof(ArticlePage),
    typeof(ArticleListPage),
    // ... etc.
};

if (knownTypes.Contains(this.Page.GetType())
{
   //Do something fantastic
}

EDIT: , , 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
}
+4

, () ( ) - , , .

:

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);
+3

( , , ), Reflection, :

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

IsAssignableFrom , , is.

+2

All Articles