如何通过字符串名称对静态类使用GetType并检查属性是否存在
解决通过字符串检查静态类成员对应类型的属性存在性问题
核心实现代码
要实现根据传入的静态成员名称字符串,检查对应对象是否包含Id属性,可以按以下步骤编写方法:
using System.Reflection; public bool CheckTableHasId(string tableName) { // 获取Schema静态类的Type对象 Type schemaType = typeof(Schema); // 查找指定名称的公开静态字段(匹配Schema里的Customers/Invoices) FieldInfo tableField = schemaType.GetField(tableName, BindingFlags.Public | BindingFlags.Static); if (tableField == null) { // 传入的表名称不存在,可根据需求返回false或抛出异常 return false; } // 获取静态字段的实例对象(静态字段无需实例,GetValue参数传null) object tableInstance = tableField.GetValue(null); if (tableInstance == null) { return false; } // 检查该实例类型是否包含Id属性 PropertyInfo idProperty = tableInstance.GetType().GetProperty("Id"); return idProperty != null; }
关键说明
- 字段查找逻辑:使用
BindingFlags.Public | BindingFlags.Static确保能正确定位Schema类中的公开静态只读字段。 - 静态字段取值:静态成员不属于任何类实例,因此
GetValue方法传入null即可获取字段值。 - 异常处理:如果传入的
tableName不存在于Schema中,GetField会返回null,可根据业务需求调整处理逻辑(比如抛出ArgumentException提示非法参数)。
使用示例
// 检查Customers表是否有Id属性,返回true bool customersHasId = CheckTableHasId("Customers"); // 检查Invoices表是否有Id属性,取决于InvoiceTable类的定义 bool invoicesHasId = CheckTableHasId("Invoices");
内容的提问来源于stack exchange,提问作者user2208746
相关产品推荐
相关产品推荐

