方法解释
-
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 不是基本类型} }