如何查找任意类的直接基类?如何实现支持类型继承的属性存储对象?
问题2:创建支持继承链查找的属性存储对象
这个需求很实用,我们可以设计一个基于字典的存储类,结合反射遍历类型的继承链,实现“找不到当前类型就找最接近的基类”的逻辑。
实现代码
using System; using System.Collections.Generic; public class TypePropertyStore { // 用字典存储类型和对应的字符串属性 private readonly Dictionary<Type, string> _propertyCache = new Dictionary<Type, string>(); // 设置指定类型的属性 public void SetProperty<T>(string propertyValue) { var targetType = typeof(T); _propertyCache[targetType] = propertyValue; } // 获取指定类型的属性(找不到则遍历基类) public string GetProperty<T>() { Type currentType = typeof(T); // 从当前类型开始,向上遍历继承链 while (currentType != null) { if (_propertyCache.TryGetValue(currentType, out string value)) { return value; } // 移动到直接基类 currentType = currentType.BaseType; } // 如果整个继承链都没找到,返回null(也可以根据需求抛出异常) return null; } }
使用示例
// 实例化存储对象 var propertyStore = new TypePropertyStore(); // 给基类和object设置属性 propertyStore.SetProperty<Animal>("动物的通用属性"); propertyStore.SetProperty<object>("根类型默认属性"); // 获取Dog类型的属性(Dog本身没设置,所以返回Animal的属性) string dogProp = propertyStore.GetProperty<Dog>(); Console.WriteLine(dogProp); // 输出:动物的通用属性 // 获取int类型的属性(int的基类是ValueType,ValueType的基类是object,所以返回object的属性) string intProp = propertyStore.GetProperty<int>(); Console.WriteLine(intProp); // 输出:根类型默认属性 // 获取一个完全没设置过的类型,比如string string stringProp = propertyStore.GetProperty<string>(); Console.WriteLine(stringProp); // 输出:根类型默认属性
扩展说明
如果需要支持接口的属性查找(比如某个类实现的接口有对应的属性),可以在遍历继承链的同时,遍历当前类型实现的所有接口,不过这会增加复杂度,你可以根据实际需求调整逻辑。另外,如果要支持泛型定义(比如List<>而非List<string>),可以在遍历的时候检查currentType.IsGenericType,然后获取currentType.GetGenericTypeDefinition()去字典里查找。
内容的提问来源于stack exchange,提问作者Matthew Busche
相关产品推荐
相关产品推荐

