pre-defined constants for non-trivial data types

后端 未结 4 1828
梦如初夏
梦如初夏 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; }
    }
    

提交回复
热议问题