如何在ASP.NET Core MVC中将仅含布尔属性的实体转换为List<bool>
解决方案
1. 修正实体类定义
你当前的实体类存在属性重名的问题,先修正为正确的属性名:
namespace MyProject.Entities { public class MyEntity { public bool Bool1 { get; set; } public bool Bool2 { get; set; } public bool Bool3 { get; set; } } }
2. 实现转换逻辑
提供两种实现方案,可根据你的场景选择:
方案一:强类型扩展方法(推荐,性能更高、顺序可控)
新增静态扩展类实现ToList方法:
using MyProject.Entities; using System.Collections.Generic; namespace MyProject.Extensions { public static class MyEntityExtensions { public static List<bool> ToList(this MyEntity entity) { // 可自行调整属性的返回顺序 return new List<bool> { entity.Bool1, entity.Bool2, entity.Bool3 }; } } }
方案二:反射通用实现(适合后续会新增布尔属性的场景)
如果后续可能给实体新增布尔属性,不想每次都修改扩展代码,可以用反射实现:
using System; using System.Collections.Generic; using System.Reflection; using System.Linq; namespace MyProject.Extensions { public static class EntityExtensions { public static List<bool> GetBoolPropertiesToList(this object entity) { if (entity == null) throw new ArgumentNullException(nameof(entity)); // 按属性名排序保证返回顺序稳定,可自行调整排序逻辑 return entity.GetType() .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.PropertyType == typeof(bool)) .OrderBy(p => p.Name) .Select(p => (bool)p.GetValue(entity)) .ToList(); } } }
3. 调用方式
引入扩展方法所在的命名空间后即可调用:
using MyProject.Entities; using MyProject.Extensions; // 必须引入扩展类的命名空间 using System.Collections.Generic; namespace MyProject { public class Program { public static void Main(string[] args) { MyEntity myEntity = new MyEntity() { Bool1 = true, Bool2 = false, Bool3 = false }; // 方案一调用 List<bool> boolList = myEntity.ToList(); // 方案二调用 // List<bool> boolList = myEntity.GetBoolPropertiesToList(); } } }
内容的提问来源于stack exchange,提问作者tsukittt
相关产品推荐
相关产品推荐

