在 C# 中,可以使用 typeof 运算符来检测变量的类型。以下是一个示例:

int number = 10;
Console.WriteLine(number.GetType()); // 输出:System.Int32

string name = 'John';
Console.WriteLine(name.GetType()); // 输出:System.String

bool isTrue = true;
Console.WriteLine(isTrue.GetType()); // 输出:System.Boolean

另外,还可以使用 is 关键字来检测变量的类型,例如:

int number = 10;
if (number is int)
{
    Console.WriteLine('number is an int');
}

string name = 'John';
if (name is string)
{
    Console.WriteLine('name is a string');
}

bool isTrue = true;
if (isTrue is bool)
{
    Console.WriteLine('isTrue is a boolean');
}

这样就可以根据变量的类型执行相应的操作。

C# 变量类型检测:typeof 和 is 关键字

原文地址: https://www.cveoy.top/t/topic/bjNK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录