逻辑: 检查该类型是否是基本类型或其他指定的类型(如字符串、日期、枚举等)。 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;// 如果是数组类型,检查数组中的每个元素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()){// 获取属性值并递归检查object propertyValue = property.GetValue(obj);if (!OnlyPrimitiveTypes(propertyValue)){return false; // 如果任一属性不是基本类型,则返回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 不是基本类型}
}