Refection.Emit
October 5, 2002 Written by Charles CookReflection.Emit is cool. For example, the XML-RPC.NET proxy generator has to add a custom attribute - XmlRpcMethodAttribute - to each method generated in the proxy class to specify the name of the method exposed by the XML-RPC server endpoint (the .NET method name is not necessarily the same as the method name on the XML-RPC server). I thought this might be tricky to accomplish but it was in fact trivial:
// create MethodBuilder for the method being defined
MethodBuilder mb;
...
// get the type of the custom attribute
Type customAttr = typeof(XmlRpcMethodAttribute);
// the parameter signature of the attribute constructor to be used
Type[] oneString = new Type[1] {typeof(string)};
// get a ConstructorInfo object for the required constructor
ConstructorInfo ci = customAttr.GetConstructor(oneString);
// get a CustomAttributeBuilder object, specifying the constructor parameters
CustomAttributeBuilder cab = new CustomAttributeBuilder(ci, new object[]
{XmlRpcMethodName});
// set the custom attribute on the method
mb.SetCustomAttribute(cab);
Copyright © 2011, Charles Cook.