属性参数必须是常量表达式

时间:2013-02-24 04:59:09

标签: c# interface attributes

有人可以向我解释为什么以下接口定义在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表达式或数组创建表达式

如果删除自定义属性,则不会出现编译错误。

1 个答案:

答案 0 :(得分:2)

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

此代码无法编译:

[IncompleteCodePort()]
interface IGL
{}

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

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

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

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)
    {}
}