选择数据类型作为参数

本文关键字:参数 数据类型 选择 | 更新日期: 2023-09-27 18:09:26

是否有方法指定数据类型(特别是:int, text, byte, char)作为参数?例如:(this doesn't work)

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

选择数据类型作为参数

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

CS0151 switch表达式或case标号必须是bool、char、string、integer、enum或相应的可空类型

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

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

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

同样值得注意的是,除了使用Type类之外,您还可以用int替代System.Int32。这是因为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");
}