简体   繁体   中英

“is” c# multiple options

return (
      Page is WebAdminPriceRanges ||
      Page is WebAdminRatingQuestions
);

Is there a way to do it like:

return (
    Page is WebAdminPriceRanges || WebAdminRatingQuestions
);

No, such syntax is not possible. The is operator requires 2 operands, the first is an instance of an object and the second is a type.

You could use GetType() :

return new[] { typeof(WebAdminPriceRanges), typeof(WebAdminRatingQuestions) }.Contains(Page.GetType());

Not really. You can look for the Type instance inside a collection, but that doesn't account for the implicit conversions that is performs; for example, is also detects if the type is a base of the instance it operates on.

Example:

var types = new[] {typeof(WebAdminPriceRanges), typeof(WebAdminRatingQuestions)};

// this will return false if Page is e.g. a WebAdminBase
var is1 = types.Any(t => t == Page.GetType());

// while this will return true
var is2 = Page is WebAdminPriceRanges || Page is WebAdminRatingQuestions;

不可以。您指定的第一种方式是唯一合理的方式。

不,C# 不是英语,您不能从两个操作数的操作中省略一个操作数。

No, you can not do this.

if your intent is return a Page, only if it is of type WebAdminPriceRanges or WebAdminRatingQuestions , you can easily do it with if.

For example:

if(Page is WebAdminPriceRanges || Page is WebAdminRatingQuestions)
   return Page;
return null;

Assuming that Page is a reference type or at least nullable value type

The other answers are true, but while I'm not sure where is fits in operator precedence. If the is operator is lower than the logical-or operator, you would be or-ing two classes together which is meaningless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM