2013-05-01 176 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

我不知道爲什麼您鏈接到網頁上,該文件說,不支持:

動態方法和參數沒有被命名,但您可以指定名稱來協助調試。自定義屬性在動態方法或其參數上不受支持。

相關問題