如何在未知泛型类型时通过反射获取属性的泛型特性
解决未知泛型类型下获取泛型特性并调用方法的问题
针对你的场景,有两种可行的方案来获取目标特性并调用ProcessValue方法,以下是具体实现:
方法一:通过非泛型接口实现类型安全调用
这是最简洁且性能最优的方案,通过给泛型特性添加非泛型接口,避免反射调用的开销:
// 定义非泛型接口,统一方法签名 public interface IMyTypedAttribute { object ProcessValue(object value); } // 让泛型特性实现该接口 public class MyTypedAttribute<TValue> : Attribute, IMyTypedAttribute { public virtual TValue ProcessValue(object value) { // 原泛型方法实现,示例返回默认值 return default(TValue); } // 显式实现非泛型接口,内部调用泛型版本 object IMyTypedAttribute.ProcessValue(object value) { return ProcessValue(value); } } // 子类无需修改,自动继承接口实现 public class MyNumberAttribute : MyTypedAttribute<int> { public override int ProcessValue(object value) { return int.TryParse(value?.ToString(), out var num) ? num : 0; } } public class MyStringAttribute : MyTypedAttribute<string> { public override string ProcessValue(object value) { return value?.ToString() ?? string.Empty; } }
获取特性并调用方法的代码:
PropertyInfo myProp = ...; // 获取所有实现IMyTypedAttribute的特性 var typedAttributes = myProp.GetCustomAttributes(typeof(IMyTypedAttribute), inherit: false) .Cast<IMyTypedAttribute>(); foreach (var attr in typedAttributes) { object result = attr.ProcessValue(yourInputValue); // 根据返回值实际类型处理结果 if (result is int intResult) { // 处理int类型结果 } else if (result is string strResult) { // 处理string类型结果 } }
方法二:通过反射直接调用方法
如果无法修改原特性类,可以直接通过反射定位并调用ProcessValue方法:
PropertyInfo myProp = ...; // 筛选所有继承自MyTypedAttribute<>的特性 var targetAttributes = myProp.GetCustomAttributes() .Where(attr => attr.GetType().IsSubclassOf(typeof(MyTypedAttribute<>))); foreach (var attr in targetAttributes) { // 获取特性类型中的ProcessValue方法 MethodInfo processMethod = attr.GetType() .GetMethod(nameof(MyTypedAttribute<int>.ProcessValue)); if (processMethod != null) { object result = processMethod.Invoke(attr, new object[] { yourInputValue }); // 根据result的实际类型做后续处理 } }
补充说明
你之前遇到的问题原因:
- 未绑定的泛型类型
MyTypedAttribute<>不能作为GetCustomAttribute<T>的泛型参数,该方法要求传入封闭构造泛型类型(如MyTypedAttribute<int>)。 MyTypedAttribute<object>和MyTypedAttribute<int>是完全不同的封闭类型,不存在继承关系,因此强制转换会抛出运行时异常。
内容的提问来源于stack exchange,提问作者devklick
相关产品推荐
相关产品推荐

