具有以下代码:
class Car{}
class WV : Car{}
class BMW: Car{}
class Bike{}
class Yamaha : Bike {}
class KTM : Bike{}
void DoSomething(<some other parameters>, Type targetType){}
//I call DoSomething with:
service.DoSomething(...., typeof(BMW));
当程序员编写代码时,是否有任何方法可以强制targetype
仅用于基类Car
?
在执行过程中很容易检查,但我想强制执行我们想要的预期基类。
我希望当程序员键入:service.DoSomething(...., typeof(KTM));
时,代码在编译时会出现错误。
感谢
您可以尝试在用例中使用泛型。它看起来像:
void DoSomething<T>(<some other parameters>) where T: Car {}
service.DoSomething<BMW>(...);