C# 使用反射查找弃用
我很好奇是否有人编写了代码来反映到一个类中并找到它不推荐的方法C# 使用反射查找弃用,c#,t4,C#,T4,我很好奇是否有人编写了代码来反映到一个类中并找到它不推荐的方法 我为reactive设计了一个T4模板,希望它能停止为不推荐的事件生成处理程序,有没有聪明的黑客已经击败了我?我不知道你是否要求T4框架,但这里有一个过时标记方法的通用反射示例 class TestClass { public TestClass() { DeprecatedTester.FindDeprecatedMethods(this.GetType()); } [Obsole
我为reactive设计了一个T4模板,希望它能停止为不推荐的事件生成处理程序,有没有聪明的黑客已经击败了我?我不知道你是否要求T4框架,但这里有一个过时标记方法的通用反射示例
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);
}
}
}
}
class测试类
{
公共测试类()
{
DeprecatedTester.FindDeprecatedMethods(this.GetType());
}
[过时(“SomeDeprecatedMethod已弃用,请改用SomeNewMethod。”)]
public void SomeDeprecatedMethod(){}
[过时(“YetAnotherDeprecatedMethod已弃用,请改用SomeNewMethod。”)]
public void YetAnotherDeprecatedMethod(){}
public void SomeNewMethod(){}
}
不推荐使用公共类
{
公共静态void finddedPrecatedMethods(t型)
{
MethodInfo[]methodInfos=t.GetMethods();
foreach(MethodInfo中的MethodInfo MethodInfo)
{
object[]attributes=methodInfo.GetCustomAttributes(false);
foreach(attributes.OfType()中的ObsoleteAttribute属性)
{
WriteLine(“找到不推荐的方法:{0}[{1}]”,methodInfo.Name,attribute.Message);
}
}
}
}
您是否将反射与T4一起使用?这是。你是说被标记为过时的成员(这是反应式框架的一部分吗?)修改了T4模板以从UI委托中生成可观察的对象,它将拾取不推荐的事件,我只需要在生成时将它们过滤掉。顺便说一句,GetCustomAttributes()重载,可以使用类型参数。因此,要检查某个方法是否已弃用,只需传递typeof(obsoletateAttribute)
。我正在使用的检查程序(用于枚举值)是:return obj.GetType().GetField(obj.ToString()).GetCustomAttributes(typeof(System.obsoletateAttribute),true)。长度>0代码>