C# : 'is' キーワードと Not Ask Question のチェック

C# : 'is' キーワードと Not Ask Question のチェック

これは馬鹿げた質問ですが、このコードを使用して、何かが特定のタイプであるかどうかを確認できます...

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

はい、はい...バカな質問ですね...

コードがどのようになっているかについては疑問があるため、メソッドの先頭で単純に return するだけです。

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

ベストアンサー1

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

おすすめ記事