2013-05-01 177 views
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 
{   
} 
+0

[如何将自定义属性添加到DynamicMethod生成的方法?](http://stackoverflow.com/questions/1145123/how-to-add-custom-attributes-to-a-dynamicmethod - 生成方法) – 2013-05-01 05:49:26

回答

0

我不知道为什么您链接到网页上,该文件说,不支持:

动态方法和参数没有被命名,但您可以指定名称来协助调试。自定义属性在动态方法或其参数上不受支持。

相关问题