日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C?sharp?(#)?數據類型獲取方式_C#教程

作者:勤奮的大熊貓 ? 更新時間: 2022-12-05 編程語言

C sharp (#) 數據類型獲取

這里研究一下關于c#中如何獲取變量類型的問題。

首先我們研究一下如何獲取單個變量的類型

// 問題一:獲取單個變量的類型
// 方法一:使用GetType()方法
public static void JudgeType()
{
? ? int element = 5;
? ? // 我們應該知道, GetType()會返回一個類型,因此我們需要用類型變量來存儲它
? ? Type type = element.GetType();
? ? // 如果我們需要判斷這個類型與其他的類型,比如與int類型,那么我們應該與typeof(int)進行比較
? ? if (type == typeof(int))
? ? {
? ? ? ? Console.WriteLine("Is the type of element int? {0}", "Yes");
? ? }
}
// =============================================
// 方法二:使用is方法
public static void JudgeType()
{
? ? // 這里為了避免warning的出現,我們使用object來定義變量
? ? object element = 5;
? ? // 使用is來直接判斷變量的類型
? ? if (element is int)
? ? {
? ? ? ? Console.WriteLine("Is the type of element int? {0}", "Yes");
? ? }
}

接下來我們研究一下如何獲取列表變量的類型

// 問題二: 獲取列表的類型
// 方法一:使用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");
? ? }
}

C#的五大數據類型

1.類(class):如Windows,Form,Console,String

2.結構體(Structures):如Int32,Int64,Single,Double

3.枚舉(Enumerations):如HorizontalAlignment,Visibility

4.接口(Interfaces)

5.委托(Delegates)

C#類型的派生譜類

原文鏈接:https://blog.csdn.net/u011699626/article/details/109164685

欄目分類
最近更新