1

我有以下课程:

[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

4

1 回答 1

1

似乎我可以将枚举装箱到一个对象并将其传递,然后取消装箱。但是,如果在解释它时没有拆箱到枚举,我只能通过抛出异常来强制执行此操作

[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;
    }
}
于 2010-05-21T12:59:46.830 回答