我有以下课程:
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ModuleActivationButtonAttribute : ExportAttribute
{
public Enum TargetRegion { get; set; }
public ModuleActivationButtonAttribute(Enum targetRegion) : base(typeof(IModuleActivationButton))
{
TargetRegion = targetRegion;
}
}
该类编译得很好,但当我用它装饰我的属性时:
[ModuleActivationButton(Regions.Tabs)]
public IModuleActivationButton ModuleActivationButton
{
get { return new ModuleActivationButton() as IModuleActivationButton; }
set { ModuleActivationButton = value; }
}
public enum Regions
{
Content,
Tabs
}
编译器吐出:
Error 1 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type C:\...\CompanyX.Modules.Home\HomeModule.cs 28 33 CompanyX.Modules.Home
答案 0 :(得分:1)
似乎我可以将enum包装到一个对象并将其作为那个传递,然后是unbox。但是,我只能通过抛出异常来强制执行此操作,如果解释它不会取消装入Enum
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ModuleActivationButtonAttribute : ExportAttribute
{
public Enum TargetRegion { get; set; }
public ModuleActivationButtonAttribute(object targetRegion) : base(typeof(IModuleActivationButton))
{
TargetRegion = targetRegion as Enum;
}
}