Я хотел бы сгенерировать следующий метод, используя DynamicMethod.Почему DynamicMethod.DefineParameter всегда возвращает значение null?
public string HelloWorld([CustomAttribute]string name)
{
return name;
}
Я пробовал следующее, но DefineParameter всегда возвращает null. Как я могу присвоить свой настраиваемый атрибут параметру.
class Program
{
static void Main(string[] args)
{
var method = new DynamicMethod("HelloWorld", typeof (string), new[] {typeof (string)});
var parameterBuilder = method.DefineParameter(1, ParameterAttributes.In, "text");
parameterBuilder.SetCustomAttribute(new CustomAttributeBuilder(typeof(CustomAttribute).GetConstructor(Type.EmptyTypes), new object[] {}));
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ret);
var temp = (Func<string,string>)method.CreateDelegate(typeof (Func<string, string>));
Console.WriteLine(temp("Hello World"));
}
}
public class CustomAttribute : Attribute
{
}
возможно дубликат [Как добавить пользовательские атрибуты к методу DynamicMethod сгенерированных?] (Http://stackoverflow.com/questions/1145123/how-to-add-custom-attributes-to-a-dynamicmethod -порожденный-метод) –