我很好奇是否有人写过任何代码反映到一个类中并找到它的Deprecated方法?
我已经掀起了T4模板的反应,并希望让它停止为已弃用的事件生成处理程序,任何聪明的黑客都已经打败了我的冲击力?
答案 0 :(得分:8)
我不知道您是否要求使用t4框架,但这里是Obsolete标记方法的通用反射示例。
class TestClass
{
public TestClass()
{
DeprecatedTester.FindDeprecatedMethods(this.GetType());
}
[Obsolete("SomeDeprecatedMethod is deprecated, use SomeNewMethod instead.")]
public void SomeDeprecatedMethod() { }
[Obsolete("YetAnotherDeprecatedMethod is deprecated, use SomeNewMethod instead.")]
public void YetAnotherDeprecatedMethod() { }
public void SomeNewMethod() { }
}
public class DeprecatedTester
{
public static void FindDeprecatedMethods(Type t)
{
MethodInfo[] methodInfos = t.GetMethods();
foreach (MethodInfo methodInfo in methodInfos)
{
object[] attributes = methodInfo.GetCustomAttributes(false);
foreach (ObsoleteAttribute attribute in attributes.OfType<ObsoleteAttribute>())
{
Console.WriteLine("Found deprecated method: {0} [{1}]", methodInfo.Name, attribute.Message);
}
}
}
}