2014-10-03 119 views
0

我想創造這樣的事情:CodeAttributeDeclaration - 自定義屬性

[MyAttribute(HelperClass.Param,的ResourceType = typeof運算(資源))] 公共字符串美孚 {}

如何我可以創建這個自定義屬性? 這是一張我的代碼:

var configParamAttr = new CodeAttributeDeclaration { Name = "MyAttribute", Arguments = new CodeAttributeArgument { Name = "ResourceType", Value = new CodePrimitiveExpression("typeof(Resources)") } } }; 
       currentProperty.CustomAttributes.Add(configParamAttr); 

我不知道我怎麼能投入自定義屬性「HelperClass.Param」。這是其他班級不變的。另外我的'typeof(資源)是結果字符串:

[MyAttribute(ResourceType="typeof(Resources)")] 
     public string Foo 
     { 
     } 
    } 

感謝您的回答。

回答

0

以下代碼似乎工作正常,它做你想做的事嗎?

using System; 

public class Program 
{ 
    public static void Main() 
    { 
     Console.WriteLine("Hello World"); 
     var a = new Foo(); 
     var b = new Foo2(); 
     var res = a.GetType().CustomAttributes; 
     foreach(var i in res) 
     { 
      Console.WriteLine(i); 
     } 
     var res2 = b.GetType().CustomAttributes; 
     foreach(var i in res2) 
     { 
      Console.WriteLine(i); 
     } 
    } 
} 

[MyAttr(typeof(int))] 
public class Foo 
{ 
} 

[MyAttr(Constants.Value,typeof(int))] 
public class Foo2 
{ 
} 

public static class Constants 
{ 
    public const int Value=1; 
} 

public class MyAttr:Attribute 
{ 
    public Type Field {get;set;} 

    public MyAttr(Type type) 
    { 
     this.Field=type; 
    } 
    public MyAttr(int a, Type type) 
    { 
     this.Field=type; 
    } 
} 
+0

我不想創建像這樣的自定義屬性。我想使用CodeAttributeDeclaration創建屬性 – ogrod87 2014-10-05 19:08:43