C#:'is' 关键字并检查 Not [英] C# : 'is' keyword and checking for Not

查看:30
本文介绍了C#:'is' 关键字并检查 Not的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个愚蠢的问题,但您可以使用此代码来检查某物是否为特定类型...

This is a silly question, but you can use this code to check if something is a particular type...

if (child is IContainer) { //....

有没有更优雅的方法来检查NOT"实例?

Is there a more elegant way to check for the "NOT" instance?

if (!(child is IContainer)) { //A little ugly... silly, yes I know...

//these don't work :)
if (child !is IContainer) {
if (child isnt IContainer) { 
if (child aint IContainer) { 
if (child isnotafreaking IContainer) { 

是的,是的...愚蠢的问题....

Yes, yes... silly question....

因为有一些问题关于代码是什么样子的,所以只是在方法开始时简单的返回.

Because there is some question on what the code looks like, it's just a simple return at the start of a method.

public void Update(DocumentPart part) {
    part.Update();
    if (!(DocumentPart is IContainer)) { return; }
    foreach(DocumentPart child in ((IContainer)part).Children) {
       //...etc...

推荐答案

if(!(child is IContainer))

是唯一的操作符(没有 IsNot 操作符).

is the only operator to go (there's no IsNot operator).

您可以构建一个扩展方法来做到这一点:

You can build an extension method that does it:

public static bool IsA<T>(this object obj) {
    return obj is T;
}

然后用它来:

if (!child.IsA<IContainer>())

你可以关注你的主题:

public static bool IsNotAFreaking<T>(this object obj) {
    return !(obj is T);
}

if (child.IsNotAFreaking<IContainer>()) { // ...

<小时>

更新(考虑 OP 的代码片段):

因为您实际上是在之后转换该值,所以您可以使用 as 代替:

public void Update(DocumentPart part) {
    part.Update();
    IContainer containerPart = part as IContainer;
    if(containerPart == null) return;
    foreach(DocumentPart child in containerPart.Children) { // omit the cast.
       //...etc...

这篇关于C#:'is' 关键字并检查 Not的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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