【问题标题】:Using Generic Types with As operator将泛型类型与 As 运算符一起使用
【发布时间】:2014-08-06 20:29:07
【问题描述】:

尝试使用 as 的泛型时出现编译器错误。既然我不能按照我想要的方式做,有什么更好的方法..?我想检查 5-6 种类型,认为我可以使用一种方法,看看它是否为空。

    T CheckIsType<T>(Thing thing)
    {
        return thing as T;
    }

确切的错误文本:

Error   1   The type parameter 'T' cannot be used with     the 'as' operator because it does not have a class type     constraint nor a 'class' constraint.

【问题讨论】:

  • 你为什么不用is
  • 我希望能够使用该变量,而不是在它不为空时强制转换。 (除了跟随 Troelsen 之外,这似乎是第一次使用泛型的好机会)
  • 最好先查看 MSDN -Compiler Error CS0413...
  • @sdiguana 你正在使用as进行投射
  • 至少在我看来,这似乎更有效率。否则我需要在 is 为真时进行硬转换(或使用 as),在使用多种类型多次执行之后,上面的方法似乎代码更少。也许它会变成一个坏主意,但是,嗯,只能通过做错几次来学习。 (我非常感谢您的指导,希望您不介意我现在会尝试留下来)。

标签: c# generics


【解决方案1】:

我想你想改用is

 var isAThing = thing is Thing;

【讨论】:

    【解决方案2】:

    只需添加它抱怨不存在的约束:

    T CheckIsType<T>(Thing thing)
        where T: class
    {
        return thing as T;
    }
    

    【讨论】:

    • 完美!我以前没用过。
    【解决方案3】:

    as 不适用于 T 可以是的值类型(如 int)。

    在这种情况下,你只需要一个泛型类型参数:

    T CheckIsType<T>(Thing thing) where T: class
    {
       return thing as T;
    }
    

    【讨论】:

    • 你还需要class
    • @DanielA.White class 而不是new 确实是正确的。固定!
    猜你喜欢
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 2016-06-10
    • 2011-09-29
    • 2019-10-02
    • 2010-09-08
    相关资源
    最近更新 更多