我正在研究一个涉及检索给定类型的方法的库。我一直在使用Type.GetMethods
,但我注意到了一个问题。假设给定类型中的方法使用 a ConditionalAttribute
,并且此条件的值为 false。GetMethods 仍将包含此方法,但我想忽略它。
这是我正在尝试的一个简单示例。这个程序在调试模式下运行,所以我想找到一种方法,只调用 foo() 和 fooDebug() 而忽略 fooBar()。
using System;
using System.Diagnostics;
using System.Reflection;
namespace ConsoleApplication
{
class ClassA
{
public static void foo()
{
Console.WriteLine("foo");
}
[Conditional("DEBUG")]
public static void fooDebug()
{
Console.WriteLine("fooDebug");
}
[Conditional("BAR")]
public static void fooBar()
{
Console.WriteLine("fooBar");
}
}
class Program
{
//In this example, I want to find a way where only foo() and fooDebug() are called and fooBar() is ignored, when reflected.
static void Main(string[] args)
{
//Call methods directly.
//Methods are called/ignored as expected.
ClassA.foo();//not ignored
ClassA.fooDebug();//not ignored
ClassA.fooBar();//ignored
//Call methods with reflection
MethodInfo[] methods = typeof(ClassA).GetMethods(BindingFlags.Static | BindingFlags.Public);
foreach (MethodInfo method in methods)
{
//All methods are called, regardless of the ConditionalAttribute.
method.Invoke(null, null);
//I figured there would be some workaround like this:
ConditionalAttribute conditional =
Attribute.GetCustomAttribute(method, typeof(ConditionalAttribute)) as ConditionalAttribute;
if (conditional == null)
{
//The method calls if it has no ConditionalAttribute
method.Invoke(null, null);
}
else
{
//I can get the string of the condition; but I have no idea how, at runtime, to check if it's defined.
string conditionString = conditional.ConditionString;
//I also cannnot do a hardcoded (conditionString == "BAR") because the library would not know about BAR
bool conditionIsTrue = true;
//conditionIsTrue = ??
//If the method has a ConditionalAttribute, only call it if the condition is true
if (conditionIsTrue)
{
method.Invoke(null, null);
}
}
}
}
}
}
最终,我想知道哪些方法不包含错误的 ConditionalAttributes。
编辑
这个想法适用于其他人会使用的库,因此假设 ClassA 是他们定义并传递到我的库中的类型。