int number = 10;Type type = typeof(number);Console.WriteLine(type); // 输出:System.Int322. GetType() 方法Get">

c#怎么判断数据类型

来源:这里教程网 时间:2026-02-21 16:48:17 作者:

如何判断 C# 中数据的类型

在 C# 中,判断数据类型有以下几种方法:

1. typeof 操作符

typeof 操作符返回指定表达式的类型。例如:

<code class="c#">int number = 10;
Type type = typeof(number);
Console.WriteLine(type); // 输出:System.Int32</code>

2. GetType() 方法

GetType() 方法返回表示当前对象类型的 Type 对象。例如:

<code class="c#">object obj = new object();
Type type = obj.GetType();
Console.WriteLine(type); // 输出:System.Object</code>

3. is 操作符

is 操作符检查表达式是否与指定的类型兼容。例如:

<code class="c#">string text = "Hello";
bool isString = text is string;
Console.WriteLine(isString); // 输出:True</code>

4. as 操作符

as 操作符尝试将表达式转换为指定的类型。如果转换成功,它会返回转换后的值;否则返回 null。例如:

<code class="c#">object obj = 10;
int? number = obj as int?;
if (number.HasValue)
{
    Console.WriteLine(number.Value); // 输出:10
}</code>

5. switch 语句

switch 语句可以根据表达式的类型执行不同的代码块。例如:

<code class="c#">object obj = 10;
switch (obj)
{
    case int number:
        Console.WriteLine("整数:" + number);
        break;
    case string text:
        Console.WriteLine("字符串:" + text);
        break;
    default:
        Console.WriteLine("其他类型");
        break;
}</code>

相关推荐