Home > Enterprise >  use .NET reflection to know if a method is not a set property and not from a base class
use .NET reflection to know if a method is not a set property and not from a base class

Time:08-30

I am using a castle windsor interceptor to try and start and finish a transaction for all public methods.

I have this Intercept method:

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.

How can I tell it is a property and is there a way to know if this in a base class?

CodePudding user response:

To tell whether a method is inherited or not, you can compare the DeclaringType with the actual object type. I'm not sure about the Castle-Windsor part, but it should be something like this

invocation.TargetType == method.DeclaringType

For property accessors the IsSpecialName property is equal to true.

!method.IsSpecialName

together

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