I have an application where I have a method taking a PropertyInfo parameter and would like to call this method from IL. For similar methods taking a MethodInfo, for example, I can create an intermediate method taking a RuntimeMethodHandle and use GetMethodFromHandle. The IL can then use Ldtoken to pass the handle.
However, there does not appear to be an equivalent metadata token for properties. I can see why this might be the case (since properties are really just a way of bundling methods together and never ‘called’ from IL), but there is definitely property metadata associated with the type. I have access to this property metadata at Emit-time, so I’d like a way to be able to pass this directly without having to resort to Reflection by name at runtime (i.e. emit Reflection calls to GetProperty taking a string that will execute at runtime.) Is there a way to do this?
Per a request in the comments, here is the application:
I’m creating an adaptor class that exposes a property reference as its component bits via a bool this[int index] property. My application compiles PLC code to a .NET assembly and so I’m trying to create diagnostic accessors that approximate the easy bitwise access provided by the PLC (where you write MyTag.2 to indicate bit 2 of tag MyTag.) This syntax can’t be used for consumption by C#, but PLC.GetBits().MyTag[2] is a reasonable approximation.
My original approach was implemented using PropertyInfo (which is how I encountered this issue), but I can certainly work around it by passing the applicable metadata from the PropertyInfo as multiple parameters. I was mainly just curious to see if it was possible to pass the PropertyInfo directly, since I hadn’t ever run into this before.
No, I don’t think you can. I say this in part through familiarity with that API, and in part because the
Expressioncompiler in the C# compiler still uses reflection when it refers to aPropertyInfo, but uses more direct methods (ldtokenetc) when referring to types and methods (for example, a getter/setter). I suspect the C# compiler team would have used it if it existed.However, in most common IL-emit scenarios, it is not necessary to pass around a
PropertyInfo. options:MethodBaseto get the getter or setter (methods can be fetched by token), and infer the property by name (not 100% robust, but should usually work)