如何确定值类型的类型
本文关键字:类型 何确定 | 更新日期: 2023-09-27 18:26:49
如何在C#中找到值类型的Type
?
假设我有:
string str;
int value;
double doubleValue;
是否有一个方法可以返回这些值类型中任何一个的Type?
更清楚地说,我正在尝试这样的东西:
string str = "Hello";
string typeOfValue = <call to method that returns the type of the variable `str`>
if (typeOfValue == "string") {
//do something
} else {
//raise exception
}
如果输入的值不是string
、int
或double
(取决于我的条件),我希望从用户那里获得输入并引发异常。
我试过:
public class Test
{
public static void Main(string[] args)
{
int num;
string value;
Console.WriteLine("Enter a value");
value = Console.ReadLine();
bool isNum = Int32.TryParse(value, out num);
if (isNum)
{
Console.WriteLine("Correct value entered.");
}
else
{
Console.WriteLine("Wrong value entered.");
}
Console.ReadKey();
}
}
但是如果我要检查的值的类型是string
或其他什么呢?
您可以在.Net中的任何元素上使用GetType
,因为它存在于对象级别:
var myStringType = "string".GetType();
myStringType == typeof(string) // true
GetType返回一个Type
对象,您可以通过使用Type
上的Name
属性来获得可读的人类友好名称。
GetType
将返回正确的结果:
string typeOfValue = value.GetType().ToString();
但在这种情况下,您不需要将类型转换为字符串进行比较:
if (typeof(String) == value.GetType()) ...