C# CodeAttributeDeclaration-自定义属性
我想创造这样的东西: [MyAttribute(HelperClass.Param,ResourceType=typeof(Resources))] 公共字符串Foo { } 如何创建此自定义属性? 这是我的一段代码:C# CodeAttributeDeclaration-自定义属性,c#,.net,C#,.net,我想创造这样的东西: [MyAttribute(HelperClass.Param,ResourceType=typeof(Resources))] 公共字符串Foo { } 如何创建此自定义属性? 这是我的一段代码: var configParamAttr = new CodeAttributeDeclaration { Name = "MyAttribute", Arguments = new CodeAttributeArgument { Name = "ResourceType", V
var configParamAttr = new CodeAttributeDeclaration { Name = "MyAttribute", Arguments = new CodeAttributeArgument { Name = "ResourceType", Value = new CodePrimitiveExpression("typeof(Resources)") } } };
currentProperty.CustomAttributes.Add(configParamAttr);
我不知道如何将自定义属性“HelperClass.Param”放入其中。这是其他类的常量。其他my’typeof(资源)为结果中的字符串:
[MyAttribute( ResourceType="typeof(Resources)")]
public string Foo
{
}
}
谢谢您的回答。下面的代码似乎工作得很好,它能满足您的需要吗
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;
}
}
我不想创建这样的自定义属性。我想使用CodeAttributeDeclaration创建属性