我正在使用 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;