【问题标题】:Choosing a data type as a parameter? [duplicate]选择数据类型作为参数? [复制]
【发布时间】:2015-11-16 00:47:19
【问题描述】:

有没有办法将数据类型(特别是:int、text、byte、char)指定为参数? 例如:(这不起作用)

public void myclass(System.Object ChoosenType)
{
    switch (ChoosenType)
        case System.Text:
        case System.Byte:
        case System.Int32:
        case Sustem.Char:
}

【问题讨论】:

  • 听起来像XY problem。你想达到什么目的?在我看来,代码味道很糟糕。
  • 抱歉重复了。我有点新,所以我的词汇量不足。

标签: c#


【解决方案1】:

另外值得注意的是,除了使用Type 类之外,您还可以将System.Int32 替换为其别名int。这是可行的,因为int 实际上只是完全限定的System.Int32 类的“昵称”。

前-

public void myClass(Type x)
{
    if (x == typeof(int))
    {
        Console.WriteLine("int");
    }
    else if (x == typeof(bool))
    {
        Console.WriteLine("bool");
    }
    else if (x == typeof(string))
    {
        Console.WriteLine("string");
    }
    //additional Type tests can go here
    else Console.WriteLine("Invalid type");
}

【讨论】:

    【解决方案2】:

    您可以使用Type 类。但是,您不能使用 switch 语句,因为您无法打开 Type 对象。

    CS0151 switch 表达式或 case 标签必须是 bool、char、string、integral、enum 或相应的可为 null 类型

    您还需要更改比较方法,因为类型的“类型名称”不是Type 对象。你必须使用typeof:

    public void someMethod(Type theType)
    {
        if (theType == typeof(Int32))
        {
        }
        else if (theType == typeof(Char))
        {
        }
        ...
    }
    

    还要注意System.Text 不是一个类型,而是一个命名空间。另一方面,System.String 是一种类型。

    【讨论】:

      猜你喜欢
      • 2014-09-24
      • 1970-01-01
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      相关资源
      最近更新 更多