C sharp (#) 数据类型获取
// 问题二: 获取列表的类型
// 方法一:使用GetType()方法
public static void JudgeType()
{
// 创建一个列表对象
var list = new List<int>() { 1, 2 };
Type type = list.GetType();
if (type == typeof(List<int>))
{
Console.WriteLine("Is the type of list List<int>? {0}", "Yes");
}
}
// ================================================================================================================
// 方法二:使用is方法
public static void JudgeType()
{
var list = new List<int>() { 1, 2 };
if (list is List<int>)
{
Console.WriteLine("Is the type of list List<int>? {0}", "Yes");
}
}
// ================================================================================================================
// 方法三:使用GetType()和GetGenericArguments()方法
public static void JudgeType()
{
var list = new List<int>() { 1, 2 };
Type[] type = list.GetType().GetGenericArguments();
if (type[0] == typeof(int))
{
Console.WriteLine("Is the type of list List<int>? {0}", "Yes");
Console.WriteLine("Is the type of element in list int? {0}", "Yes");
}
}
// ================================================================================================================
// 方法四: 使用GetType()和ToString()方法
public static void JudgeType()
{
var list = new List<int>() { 1, 2 };
foreach (var element in list)
{
Type type1 = element.GetType();
if (type1.ToString() == "System.Int32")
{
Console.WriteLine("Is the type of element in list int? {0}", "Yes");
}
}
}
// ================================================================================================================
// 方法五: 使用GetType()和Name方法
public static void JudgeType()
{
var list = new List<int>() { 1, 2 };
string type_ = list[0].GetType().Name;
Console.WriteLine(type_);
if (type_ == "Int32")
{
Console.WriteLine("Is the type of element in list int? {0}", "Yes");
}
}