我正在使用Unity進行截取。因爲我有很多接口,我不得不使用VirtualMethodInterceptor
。在我的行爲中,我只想在所調用的方法在特定類型的接口(具有特殊屬性)中聲明時作出反應。我認爲MethodBase.DeclaringType可以解決我的問題,但它的行爲與我所期望的不同。它返回實現類型。如何查找聲明方法的接口
我可以同意,它是有道理的,因爲該方法可以在多個接口中聲明,但應該有一種方法來輕鬆獲取它們的列表。不幸的是,我還沒有找到它。
小樣本顯示我的問題
public interface ISample
{
void Do();
}
public class Sample : ISample
{
public void Do()
{
}
}
class Program
{
static void Main(string[] args)
{
var m = typeof(Sample).GetMethod("Do") as MethodBase;
Console.WriteLine(m.DeclaringType.Name); // Prints "Sample"
}
}
一個尷尬的解決方案:
var interfaces = from i in input.MethodBase.DeclaringType.GetInterfaces()
where i.GetCustomAttributes(typeof(CustomAttribute), true).Length > 0
where i.GetMethod(input.MethodBase.Name, input.MethodBase.GetParameters().Select(p=>p.ParameterType).ToArray()) != null
select i;
發佈您的尷尬解決方案作爲答案並接受它。尷尬的要求有尷尬的解決方案。 –
但我真的需要枚舉所有接口和所有參數。我不知道這是否是一個尷尬的要求,但我期望從運行時獲得更好的幫助。 – StanislawSwierc