C#:'是'关键字并检查不是

这是一个愚蠢的问题,但你可以使用这段代码来检查是否某种特定的types…

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

有没有更好的方法来检查“NOT”实例?

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

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

因为在代码的外观上存在一些问题 ,所以这只是方法开始时的一个简单的返回。

 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运营商)。

你可以build立一个扩展方法来做到这一点:

 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的代码片段):

既然你实际上在之后投射这个价值,你可以使用:

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

你可以这样做:

 object a = new StreamWriter("c:\\temp\\test.txt"); if (a is TextReader == false) { Console.WriteLine("failed"); } 

为什么不使用其他的?

 if (child is IContainer) { // } else { // Do what you want here } 

它整洁它熟悉和简单?

你有这样的方式是好的,但你可以创build一套扩展方法,以“一个更优雅的方式来检查”不“实例。”

 public static bool Is<T>(this object myObject) { return (myObject is T); } public static bool IsNot<T>(this object myObject) { return !(myObject is T); } 

然后你可以写:

 if (child.IsNot<IContainer>()) { // child is not an IContainer } 

享受,罗伯特C. Cartaino

丑陋? 我不同意。 唯一的方法(我个人认为这是“丑陋的”):

 var obj = child as IContainer; if(obj == null) { //child "aint" IContainer } 

is运算符是一个布尔结果,所以你可以做任何你可以在bool上做的事情。 否定它使用! 运营商。 为什么你想要有一个不同的运营商为此?

虽然信息系统运营商通常是最好的方式,但在某些情况下还有其他的select。 您可以使用as运算符并testingnull。

 MyClass mc = foo as MyClass; if ( mc == null ) { } else {} 

扩展方法IsNot<T>是扩展语法的好方法。 记住

 var container = child as IContainer; if(container != null) { // do something w/ contianer } 

performance要好于做类似的事情

 if(child is IContainer) { var container = child as IContainer; // do something w/ container } 

在你的情况下,你从方法中返回并不重要。 换句话说,注意不要同时检查types和types转换。

 if (child is IContainer ? false : true)