2014-10-03 118 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