简体   繁体   English

使用 .NET 反射来了解方法是否不是集合属性,也不是来自基类

[英]use .NET reflection to know if a method is not a set property and not from a base class

I am using a castle windsor interceptor to try and start and finish a transaction for all public methods.我正在使用城堡 Windsor 拦截器来尝试启动和完成所有公共方法的事务。

I have this Intercept method:我有这个Intercept方法:

public void Intercept(IInvocation invocation)
{
    MethodInfo method;
    try
    {
        method = invocation.MethodInvocationTarget;
    }
    catch
    {
        method = invocation.GetConcreteMethod();
    }

    if (!method.IsPublic)
    {
        return;
    }

    if (!((IList) new[] {"ncontinuity2.core", "c2.bases"}).Contains(method.DeclaringType.Assembly.GetName().Name))
    {
        return;
    }


    PerformUow(invocation);
}

I cannot find a way of excluding property set methods, for example, I have this property in a base class:我找不到排除属性集方法的方法,例如,我在基类中有这个属性:

public virtual Context Context
{
    get { return _context; }
    set
    {
        _context = value;
    }
}

I would like to exclude properties like this Set_Context .我想排除像Set_Context这样的Set_Context

How can I tell it is a property and is there a way to know if this in a base class?我怎么知道它是一个属性,有没有办法知道它是否在基类中?

To tell whether a method is inherited or not, you can compare the DeclaringType with the actual object type.要判断一个方法是否被继承,您可以将DeclaringType与实际对象类型进行比较。 I'm not sure about the Castle-Windsor part, but it should be something like this我不确定 Castle-Windsor 部分,但它应该是这样的

invocation.TargetType == method.DeclaringType

For property accessors the IsSpecialName property is equal to true .对于属性访问器, IsSpecialName属性等于true

!method.IsSpecialName

together一起

if (invocation.TargetType == method.DeclaringType && !method.IsSpecialName) {
    // We have a non-inherited method not being a property accessor.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM