pre-defined constants for non-trivial data types

后端 未结 4 1766
梦如初夏
梦如初夏 2021-01-06 18:29

My Goal: Create a C# class for predefined errors that have both an ID and a Message. Here was what I tried:

public class MyError
{
    public static readonly         


        
相关标签:
4条回答
  • 2021-01-06 19:06

    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; }
    }
    
    0 讨论(0)
  • 2021-01-06 19:10

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

    0 讨论(0)
  • 2021-01-06 19:11

    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.

    0 讨论(0)
  • 2021-01-06 19:11

    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; } }
    
    0 讨论(0)
提交回复
热议问题