0
我想用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 - 生成方法) – 2013-05-01 05:49:26