【问题标题】:Attribute argument must be a constant expression属性参数必须是常量表达式
【发布时间】:2013-02-09 12:38:48
【问题描述】:

有人可以向我解释为什么以下接口定义在 Visual Studio 2010 中编译时出错?

   [IncompleteCodePort(SourceOriginType.Other, "This should be a GL abstraction depending on what OpenGL API will be used")]
    public interface IGL
    {
        /// <summary>
        /// Returns true if provided function is available or supported by graphics API
        /// </summary>
        /// <param name="funcName"></param>
        /// <returns></returns>
        bool IsFunctionAvailable(string funcName);

        /// <summary>
        /// Returns true if provided function is supported as extension by graphics API
        /// </summary>
        /// <param name="funcName"></param>
        /// <returns></returns>
        bool IsExtensionAvailable(string funcName);
    }



public class IncompleteCodePortAttribute : Attribute
    {
        public SourceOriginType SourceOriginType { get; private set; }
        public string SourceUrl { get; private set; }
        public string Reason { get; private set; }


        public IncompleteCodePortAttribute(SourceOriginType originType, string reason, string sourceUrl = null)
        {
            SourceOriginType = originType;
            SourceUrl = sourceUrl;
            Reason = reason;
        }
    }

    public enum SourceOriginType
    {
        CodePlex,
        WorldWindJdk,
        StackOverflow,
        Other
    }

我得到的错误是:

属性参数必须是属性参数类型的常量表达式、typeof表达式或数组创建表达式

如果我删除自定义属性,我不会收到任何编译错误。

【问题讨论】:

  • 什么是IncompleteCodePort?发布它的所有构造函数。
  • 我能够使用一个虚拟的 IncompleteCodePort 类进行编译。我相信您在这里遗漏了一些信息。
  • 如果您在IncompleteCodePort 类中使用Enum,请不要。请改用SourceOriginType
  • 我的错。以这种方式发布为时已晚。我已经添加了 IncompleteCodePortAttribute 定义。
  • 这是 c# 编译器中的一个错误。它已被修复。见stackoverflow.com/questions/8290853/…

标签: c# interface attributes


【解决方案1】:

这似乎是 VS2010 中 C# 编译器中的一个错误(代码在 VS2012 下编译良好)。看起来编译器没有将参数默认值中的null 视为常量。

此代码无法编译:

[IncompleteCodePort()]
interface IGL
{}

class IncompleteCodePortAttribute : Attribute
{
    public IncompleteCodePortAttribute(string sourceUrl = null)
    {}
}

带有提到的错误消息(“属性参数必须是属性参数类型的常量表达式、类型表达式或数组创建表达式”),但没有源代码位置会令人困惑。

一些有效的属性声明示例:

class IncompleteCodePortAttribute : Attribute
{
    public IncompleteCodePortAttribute(string sourceUrl = "")
    {}
}
class IncompleteCodePortAttribute : Attribute
{
    private const string Null = null;

    public IncompleteCodePortAttribute(string sourceUrl = Null)
    {}
}
class IncompleteCodePortAttribute : Attribute
{
    public IncompleteCodePortAttribute()
        : this(null)
    {}

    public IncompleteCodePortAttribute(string sourceUrl)
    {}
}

【讨论】:

  • 谢谢。奇怪的是,我在 VS2012 中打开解决方案,回到 VS2010 并重新加载,现在它可以编译了。
  • 可以,但现在无法编译。我刚刚删除了可选的构造函数参数并重载了构造函数。谢谢。
  • 很高兴知道我们正在获得一个包含此修复的服务包...哦等等。
猜你喜欢
  • 2014-11-13
  • 1970-01-01
  • 2017-02-24
  • 2016-01-05
  • 2011-12-10
  • 2014-11-09
相关资源
最近更新 更多