CodeAttributeDeclaration-自定义属性
本文关键字:自定义属性 CodeAttributeDeclaration- | 更新日期: 2023-09-27 18:25:30
我想创建这样的东西:
[MyAttribute(HelperClass.Param,ResourceType=typeof(Resources))]公共字符串Foo{}
如何创建此自定义属性?这是我的一段代码:
var configParamAttr = new CodeAttributeDeclaration { Name = "MyAttribute", Arguments = new CodeAttributeArgument { Name = "ResourceType", Value = new CodePrimitiveExpression("typeof(Resources)") } } };
currentProperty.CustomAttributes.Add(configParamAttr);
我不知道如何将"HelperClass.Param"放入自定义属性中。这是其他类的常量。额外的my'typeof(resources)是结果中的字符串:
[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;
}
}