如何在Type中找到值类型的C#?
假设我有:
string str;
int value;
double doubleValue;是否有返回这些值类型的方法?
更清楚的是,我正在尝试这样的方法:
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或其他什么的话呢?
发布于 2014-10-16 13:07:27
您可以对GetType中的任何元素使用.Net,因为它存在于对象级别:
var myStringType = "string".GetType();
myStringType == typeof(string) // trueGetType返回一个Type对象,您可以使用Type上的Name属性获得一个可读的友好的人名。
发布于 2014-10-16 13:06:56
GetType将返回正确的结果:
string typeOfValue = value.GetType().ToString();但是在这种情况下,您不需要将类型转换为字符串以进行比较:
if (typeof(String) == value.GetType()) ...https://stackoverflow.com/questions/26405217
复制相似问题