【问题标题】:How to check type parameter?如何检查类型参数?
【发布时间】:2013-07-31 16:12:10
【问题描述】:

我有课

class ManagerCar : IBlalba
{
   public void Render(IViewTemplate template)
   {
   }
}

我知道参数模板是什么CarViewTemplate 我想检查类型并在IViewTemplate != CarViewTemplate 时抛出异常

我可以检查if(template is typeof(CarViewTemplate))

但我有很多Managers

我想在编译时检查此类型并使用[IsType(typeof(CarViewTemplate))]等帮助属性

有可能吗?

更新 我与Render(IViewTemplate template)有接口

【问题讨论】:

  • 如果您不能使用IViewTemplate,请不要接受。您要查找的编译时检查是 CarViewTemplate template
  • 我可能在这里遗漏了一些重要的东西,但是你为什么不把 tempate 参数设置为 CarViewTemplate 类型呢?
  • 一旦你开始做大量的typeof 检查,你就会知道你有代码异味。
  • 如果你有Render(IViewTemplate template)的接口,那为什么没有ManagerCar : SuchAnInterface
  • @Dimitar Dimitrov,你的声音不错

标签: c#


【解决方案1】:

这种类型的检查在编译器中已经存在,无需尝试帮助它。

只需将您的方法签名更改为:

public void RenderCar(CarViewTemplate template)

【讨论】:

  • 我实际上假设这个答案是不可用的,但这里的主要问题是这个信息(它不可用)在问题中没有以任何方式或形式说明。我假设 OP 不能只更改代码是有原因的,但由于没有详细说明,我想激发该信息出现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 2012-11-18
  • 2023-03-17
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
相关资源
最近更新 更多