【问题标题】:how to receive an type as parameter?如何接收类型作为参数?
【发布时间】:2012-01-22 01:50:11
【问题描述】:

我正在编写一个进行强制转换的方法,我需要接收一个类型作为参数,例如:

object foo(?? type, object input) { 

    if(type is x ) { 
       Output output = new Output();
       x xValue = (x) input; 
       foreach(var val xValue) { 
          //do.. 
       }

       return output; 
    }

    if(type is y) {
          Output2 output = new Output2();
          y yValue = (y) input; 

        foreach(var val yValue) { 
          //do.. 
        }

       return output;
    } else { 
      //invalid type
    }
}

【问题讨论】:

  • 键入System.Type 还是键入特定(或继承)类型的对象?
  • 一个类型为CookieCollection, CookieContainer..

标签: c# .net type-conversion


【解决方案1】:

使用 type 参数:

object foo<T>(T input) {
  if (T is x) { ...
  ...

另外,你的方法有点奇怪,你的分支似乎有很多共性,并且测试类型通常不是一个好方法。努力统一它们或将方法拆分为特定类型的重载:

Output foo(x input) ...

Output2 foo(y input) ...

...

并且,尝试使用更具体的返回类型,如上所示。

【讨论】:

    【解决方案2】:

    按照你的要求做:

    object foo(System.Type type, object input) { 
    ...
    }
    

    但是,您为什么不对每种类型使用不同的方法呢?拥有可以处理不同类型的单一方法,您可以获得什么?

    【讨论】:

      【解决方案3】:

      听起来您想要一个Type 作为输入,其中类型是input 参数的类型。如果是这样,那么最简单的方法是使用泛型函数

      object foo<T>(T input) {
        Type type = typeof(T);
        ...
      }
      

      您甚至可以有一个重载,它显式采用 Type 并将通用函数输入其中

      object foo<T>(T input) {
        return foo(typeof(T), input);
      }
      
      object foo(Type type, object input) {
        ...
      }
      

      【讨论】:

      • 你能扩展一下吗?这正是我正在寻找的。我从数据集中请求值,并要求开发人员发送要返回的变量类型,因此我的返回语句类似于 (returnType)ds.Tables[0].Rows[0][columnName]
      • @ganders 在这种情况下,您实际上需要执行以下操作T foo&lt;T&gt;() { return (T)...; }
      猜你喜欢
      • 2018-06-08
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      相关资源
      最近更新 更多