Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify whether a MethodInfo instance is a property accessor

Tags:

c#

reflection

I am writing a decorating proxy using Castle DynamicProxy. I need the proxy's interceptor to intercept only property writes (not reads) so I am checking the name of the method thusly:

public void Intercept(IInvocation invocation)
{
    if (invocation.Method.Name.StartsWith("set_")
    {
        // ...
    }

    invocation.Proceed();
}

Now this works fine but I don't like the fact my proxy has intimate knowledge of how properties are implemented: I'd like to replace the method name check with something akin to:

if (invocation.Method.IsPropertySetAccessor)

Unfortunately my Google-fu has failed me. Any ideas?

like image 851
Paul Ruane Avatar asked Oct 19 '11 09:10

Paul Ruane


1 Answers

You could check whether a property exists for which this method is the setter (untested):

bool isSetAccessor = invocation.Method.DeclaringType.GetProperties() 
        .Any(prop => prop.GetSetMethod() == invocation.Method)

(Inspiration taken from Marc's answer to a related question.)

like image 69
Heinzi Avatar answered Sep 21 '22 18:09

Heinzi