方法解釋
-
OnlyPrimitiveTypes
?方法:- 參數: 接收一個對象?
obj
?進行檢查。 - 返回值: 返回布爾值,表示對象及其所有屬性是否僅包含基本類型。
- 邏輯:
- 首先檢查?
obj
?是否為?null
,如果是,則返回?true
。 - 然后檢查?
obj
?的類型是否為基本類型,如果是,返回?true
。 - 接著檢查?
obj
?是否為集合類型,若是,則返回?false
。 - 最后,遍歷對象的所有公共屬性,遞歸調用?
OnlyPrimitiveTypes
?方法來檢查每個屬性值。如果有任何屬性值不符合基本類型條件,則返回?false
。 - 如果所有屬性都符合條件,則返回?
true
。
- 首先檢查?
- 參數: 接收一個對象?
IsPrimitiveType
?方法:
- 參數: 接收一個?
Type
?對象。 - 返回值: 返回布爾值,表示指定類型是否為基本類型。
- 邏輯: 檢查該類型是否是基本類型或其他指定的類型(如字符串、日期、枚舉等)。
using System; using System.Collections; using System.Collections.Generic; using System.Reflection;public static class TypeChecker {public static bool OnlyPrimitiveTypes(object obj){// Null值返回trueif (obj == null)return true;Type objType = obj.GetType();// 如果是基本類型,直接返回trueif (IsPrimitiveType(objType))return true;// 如果是自定義類,直接返回 falseif (objType.IsClass && innerFlag == true){return false;}// 如果是數組類型,檢查數組中的每個元素if (objType.IsArray){Array array = (Array)obj;foreach (var item in array){if (!OnlyPrimitiveTypes(item)){return false; // 如果任一元素不是基本類型,則返回false}}return true; // 所有元素都是基本類型}// 如果是集合類型,直接返回falseif (typeof(IEnumerable).IsAssignableFrom(objType)){return false; // 直接返回false}// 對于任何非基本類型的自定義對象,檢查其屬性foreach (PropertyInfo property in objType.GetProperties()){if (!OnlyPrimitiveTypes(property.GetValue(obj), true)){return false;}}// 如果所有屬性都符合條件,則返回truereturn true;}public static bool IsPrimitiveType(Type type){// 判斷基本類型,包括枚舉和字符串 if (type.IsPrimitive ||type.IsEnum ||type == typeof(string) ||type == typeof(decimal) ||type == typeof(DateTime) ||type == typeof(TimeSpan) ||type == typeof(Guid) ||type == typeof(byte) ||type == typeof(sbyte) ||type == typeof(short) ||type == typeof(ushort) ||type == typeof(int) ||type == typeof(uint) ||type == typeof(long) ||type == typeof(ulong) ||type == typeof(float) ||type == typeof(double) ||type == typeof(char)) {return true; }// 檢查是否為可空類型 if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {return IsPrimitiveType(Nullable.GetUnderlyingType(type)); } return false; // 其他情況下返回 false} }// 示例類 public class TaskAssignmentRecord {public int Id { get; set; }public string Name { get; set; }public DateTime DueDate { get; set; }public int[] Assignments { get; set; } // 這是一個數組類型 }// 測試代碼 public class Program {public static void Main(){var recordWithArray = new TaskAssignmentRecord{Id = 1,Name = "Test",DueDate = DateTime.Now,Assignments = new int[] { 1, 2, 3 } // 這里是一個數組類型};bool resultWithArray = TypeChecker.OnlyPrimitiveTypes(recordWithArray);Console.WriteLine(resultWithArray); // 輸出: true,因為 Assignments 是一個包含基本類型的數組var recordWithNonPrimitive = new TaskAssignmentRecord{Id = 1,Name = "Test",DueDate = DateTime.Now,Assignments = new int[] { 1, 2, 3, 4 } // 這里是一個數組類型};// 添加一個非基本類型的屬性var anotherRecord = new{Id = 1,Name = "Test",DueDate = DateTime.Now,NestedObject = new { Property = "Value" } // 這個是非基本類型};bool resultWithNonPrimitive = TypeChecker.OnlyPrimitiveTypes(anotherRecord);Console.WriteLine(resultWithNonPrimitive); // 輸出: false,因為 NestedObject 不是基本類型} }