11
10

More than 5 years have passed since last update.

Generic なメソッドを override できないときの回避方法

Posted at

まぁ、そもそもンなことすんな!って話なのかもですが、必要に駆られたので調査した。

NG例 其の壱

NG_01.cs
class Hoge {
    public virtual void Test<T>() where T : AnyClass {
        // 何か処理
    }
}

class Fuga : Hoge {
    public override void Test<T>() where T : AnyClass {
        // 何か処理
    }
}

親に virtual 付けて、子に override 付ければ行けるだろ!とか思ってたら…

`Fuga.Test<T>()': cannot override inherited member `Hoge.Test<T>()' because it is not marked virtual, abstract or override

激おこぷんぷん丸です。

端的に言うと、「ジェネリック制約付けてるメソッドは override でき NE-YO!」ってコトらしいです。

NG例 其の弐

NG_02.cs
class Hoge {
    public void Test<T>() where T : AnyClass {
        // 何か処理
    }
}

class Fuga : Hoge {
    public void Test<T>() where T : SomeClass {
        // 何か処理
    }
}

じゃあ T の制約変えて override 外したら行けるだろ!!とか思ってたら…

The constraints for type parameter `T' of method `Fuga.Test<T>()' must match the constraints for type parameter `T' of interface method `Hoge.Test<T>()'. Consider using an explicit interface implementation instead

ムカ着火ファイヤーでした。

NG例 其の参

NG_03.cs
class Hoge {
    public void Test<T>() where T : AnyClass {
        // 何か処理
    }
}

class Fuga : Hoge {
    public new void Test<T>() where T : SomeClass {
        // 何か処理
    }
}

そーいえば、 new とかあったなぁとか思ってやってみると…

The constraints for type parameter `T' of method `Fuga.Test<T>()' must match the constraints for type parameter `T' of interface method `Hoge.Test<T>()'. Consider using an explicit interface implementation instead

カム着火インフェルノォォォォオオウ!!!

OK例

ってコトで、こうします。

OK.cs
class Hoge {
    public void Test<T>() where T : AnyClass {
        // 何か処理
    }
}

class Fuga : Hoge {
    public new void Test<T>() where T : AnyClass {
        // 何か処理
    }
}

詳しく MSDN 読んだわけじゃないんだけど、どうやら where による型制約を設けていて、継承先クラスで引数が一緒のメソッドを定義する 場合は、 戻り値や制約の型が完全に同一じゃなきゃダメ で、 new を付けねばならんらしい。

なるほど、勉強になった。

11
10
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10