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

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

是否有一种更优雅的方式来检查<!> quot; NOT <!> quot;实例

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

您可以构建一个执行此操作的扩展方法:

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

其他提示

你可以这样做:

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
}

它整洁而熟悉又简单?

你拥有它的方式很好但你可以创建一组扩展方法来使<!>“更优雅的方式来检查'NOT'实例。<!> ;

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
}

丑?我不同意。唯一的另一种方式(我个人认为这是<!>“uglier <!>”;):

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

is运算符求值为布尔结果,因此您可以执行bool上可以执行的任何操作。要否定它,请使用!运算符。你为什么要为此设一个不同的算子呢?

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

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

比做

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

在您的情况下,从方法返回时无关紧要。换句话说,请注意不要同时检查类型,然后再进行类型转换。

虽然IS操作员通常是最好的方法,但有一种替代方案可以在某些情况下使用。您可以使用as运算符并测试null。

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

虽然这不能避免括号问题,但是为了让人们通过谷歌来到这里,应该提到的是存在更新的语法(从C#7开始),以使其余的代码更清晰:

if (!(DocumentPart is IContainer container)) { return; }
foreach(DocumentPart child in container.Children) {
    ...

这避免了双重转换,空检查,并且在范围内可以使用变量,它可以为null。

尚未提及此问题。它有效,我认为它看起来比使用!(child is IContainer)

更好
if (part is IContainer is false)
{
    return;
}
if (child is IContainer ? false : true)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top