【问题标题】:How do I inject a return type in a method that returns multiple types?如何在返回多种类型的方法中注入返回类型?
【发布时间】:2015-03-13 21:45:33
【问题描述】:
 public T SomeMethod<T>(){

   if(somecondition==something) return 999;
   if(somecondition==somethingelse) return "String";

 }

问题是这两个返回语句都会收到设计时错误,表明它们不是 T 类型。

调用者代码如下所示。

int ID = SomeMethod<int>();
string StringVaule = SomeMethod<string>();

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    问题的答案是:

    return (T)(object) 999;
    

    return (T)(object) "String";
    

    我称之为“双重演员”......

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 2021-04-13
      • 1970-01-01
      • 2016-09-09
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多