C# : 'is' keyword and checking for Not

后端 未结 12 1992
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 05:23

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

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

Is ther

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 05:56

    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(this object obj) {
        return obj is T;
    }
    

    and then use it to:

    if (!child.IsA())
    

    And you could follow on your theme:

    public static bool IsNotAFreaking(this object obj) {
        return !(obj is T);
    }
    
    if (child.IsNotAFreaking()) { // ...
    

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

提交回复
热议问题