简体   繁体   English

C#禁止上传

[英]C# prohibit upcast

Is there a way to prohibit implicit upcast of a paticular class ? 有没有一种方法可以禁止隐性地改造特定的阶层?

I want the compiler to throw an error if a function accepting MyBase is passed an instance of MyDerived (same for assignment etc) 如果将接受MyBase的函数传递给MyDerived的实例(对于赋值等),我希望编译器抛出错误。

My use case is trying immitate c++ typedef by inheriting but upcasting break this. 我的用例试图通过继承来模仿c ++ typedef,但是向上转换打破了这一点。

No. You can't do that on compile time. 不。您不能在编译时这样做。 It is a derived class after all. 毕竟,它是派生类。 It it its purpose to do so. 这样做的目的是。 You can on run time, but I don't think you want that. 您可以在运行时运行,但我认为您不希望这样做。

You can make MyBase sealed if you don't want any derived type to exist. 如果您不希望存在任何派生类型,则可以使MyBase密封。

I do wonder why you would want this, but that is a whole different question... 我确实想知道为什么你会想要这个,但这是一个完全不同的问题...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM