pre-defined constants for non-trivial data types

不问归期 提交于 2019-12-01 00:16:23

Your type is not mutable, but Code Analysis doesn't know that.
This warning is a false positive; you should suppress it.


To answer your edited question:

const can only be applied to primitives.
For custom types, static readonly is the only option.

As long as the type is properly immutable, it will work perfectly.

The type is not mutable. The Code Analysis gets confused by having public readonly fields.

You can fix the code analysis issue by making your public fields public properties:

public MyError(int id, string message)
{
    this.id = id;
    this.message = message;
}
private readonly int id;
private readonly string message;
public int Id { get { return id; } }
public string Message { get { return message; } }

Your properties should not be static because every instance of this class will have their own ID and Message, do you agree?

I would create a class that

  • is sealed, to prevent it from being inherited
  • has a private constructor, to prevent it from being instantiated from outside of the class
  • provides properties with private setters, so they cannot be set from outside.

That would give you the following code:

public sealed class MyError
{
    public static readonly MyError OK = new MyError(0, "OK");

    public static readonly MyError Bad = new MyError(1, "Bad Stuff");

    private MyError(int id, string message)
    {
        this.ID = id;
        this.Message = message;
    }

    public int ID { get; private set; }

    public string Message { get; private set; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!