检查对象是否与给定列表中的任何类型匹配的替代方法 [英] Alternative way of checking if an object is a match for any types in a given list

查看:158
本文介绍了检查对象是否与给定列表中的任何类型匹配的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  if(this.Page是ArticlePage || this.Page是ArticleListPage)
{
//做一些梦幻的
}

上面的代码工作,但考虑到可能有很多不同的类,我想比较 this.Page 到,我想将这些类存储在一个列表中,然后在列表中执行 .Contains()。 / p>

我该如何实现?我会使用 GetType()不知何故?我可以存储页面对象的列表,然后比较类型吗?



注意:假设所有我比较的类 this.Page 来延伸

解决方案

此代码将执行此操作:

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

if(knownTypes.Contains(this.Page.GetType())
{
//做一些梦幻的
}

编辑:正如Chris指出的,你可能想考虑类型继承,以完全模仿的行为 operator。这有点慢,但对于某些用途可能更有用:

  Type [] knownTypes = new Type [] 
{
typeof(articlePage),
typeof(ArticleListPage),
// ...
};

var pageType = this.Page.GetType();
if(knownTypes.Any(x => x.IsAssignableFrom(pageType)))
{
// Do something fantastic
}


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

The above code works, but given the fact there could be many different classes I'd want to compare this.Page to, I would like to store the classes in a list and then perform a .Contains() on the list.

How would I achieve this? Would I use GetType() somehow? Could I store a list of Page objects and then compare the types somehow?

Note: You can assume all of the classes I'm comparing this.Page to extend Page.

解决方案

This code will do the job:

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

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

EDIT: As pointed by Chris, you may want to consider type inheritance to fully mimic the behavior of is operator. That's a bit slower but can be more useful for some purposes:

Type[] knownTypes = new Type[] 
{ 
    typeof(ArticlePage), 
    typeof(ArticleListPage),
    // ... etc.
};

var pageType = this.Page.GetType();
if (knownTypes.Any(x => x.IsAssignableFrom(pageType)))
{
    //Do something fantastic
}

这篇关于检查对象是否与给定列表中的任何类型匹配的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆