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

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

问题描述

这是一个愚蠢的问题,但您可以使用此代码来检查,如果事情是一种特殊类型...

 如果(孩子的IContainer){// ... 

有没有更优雅的方式来检查为NOT比如?

 如果(!(孩子的IContainer)){//有点难看......傻,是的,我知道...... 

//这些不工作:)
如果(孩子!是的IContainer){
如果(孩子的心不是的IContainer){
如果(孩子AINT的IContainer){
如果(孩子isnotafreaking的IContainer){

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



因为没有对代码是什么样子的一些问题,它只是一个简单的回归。一个方法的开始。

 公共无效更新(Do​​cumentPart部分){
part.Update();
如果(!(DocumentPart是的IContainer)){返回; }
的foreach(DocumentPart孩子((的IContainer)的一部分)。儿童){
// ...等等...


解决方案

 如果(!(孩子的IContainer))

是去(有没有 IsNot运算运营商)的唯一运营商。



您可以构建做它的扩展方法:

 公共静态布尔ISA< T> (此对象OBJ){
返回obj是笔;
}



,然后用它来:

 如果(child.IsA<!的IContainer>())

和您可以按照您的主题:

 公共静态布尔IsNotAFreaking< T>(此对象OBJ){ !
回报率(obj为T);
}

如果(child.IsNotAFreaking<&的IContainer GT;()){// ...




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



因为你实际上铸造价值之后,你可以只使用而不是:

 公共无效更新(Do​​cumentPart部分){
part.Update();
的IContainer containerPart =一部分的IContainer;
如果(containerPart == NULL)回报;
的foreach(DocumentPart孩子containerPart.Children){//省略演员。
// ...等等...


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

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

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))

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;
}

and then use it to:

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

And you could follow on your theme:

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

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


Update (considering the OP's code snippet):

Since you're actually casting the value afterward, you could just use as instead:

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#:'是'关键字和检查不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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