c# - 创建编译错误而不是运行时错误

标签 c# compiler-errors runtime-error

我的代码需要设置我的类的一个字段,但我希望该字段只设置一​​次。如果开发人员试图重置/更改它,我理想情况下希望编译器告诉我们,而不是得到运行时错误。这可能吗?

帮助解释的代码

internal class Message
    {
        private string title = string.Empty;

        public string Title
        {
            get { return title; }
            set 
            {
                if (string.IsNullOrEmpty(title))
                    title = value;
                else
                    throw new Exception("Title can only be set once!");
            }
        }
    }

如您所见,上面的代码会抛出一个异常,但这是一个运行时错误。尽管此处的示例相当简单,但编写编译器错误或警告消息的概念可能会非常有益。

最佳答案

您要求的是自定义编译器规则,AFAIK 是不可能的。 IMO 你有两个选择,一个是让它成为构造函数的一部分,这样它就只能被设置一次,例如

internal class Message
{
    public Message(string title)
    {
        Title = title;
    }

    public string Title { get; private set; }
}

另一个是保持原样,但是抛出一个更合适的异常,例如

internal class Message
{
    private string title = string.Empty;

    public string Title
    {
        get { return title; }
        set 
        {
            if (string.IsNullOrEmpty(title))
                title = value;
            else
                throw new InvalidOperationException("Title can be set only once!");
        }
    }
}

无论哪种方式,Title 属性只会被设置一次。

关于c# - 创建编译错误而不是运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13119583/

相关文章:

c++ - 使用 Nvidia GPU Computing 工具包和 Cygwin with Eclipse 编译错误

include - 获取编译器:Error-Row when the compile error occurs in an include file

python - Python 异常(除了 SyntaxError 之外)是运行时错误吗?

debugging - Haskell GHCI,似乎无法进入主模块的交互式执行

C++ Map/Set 迭代器不可递增错误

c# - Metro 应用程序的富文本编辑器

c# - 如何播种 GUID 生成?

c# - WP7 - 自定义按钮中的闪烁背景

c# - 动态地将 javascript 与 GridView 按钮绑定(bind)

generics - 使用泛型时遇到编译器错误