如何使属性设置一次且不能更改

本文关键字:一次 不能 属性 何使 设置 | 更新日期: 2023-09-27 18:13:22

我有一个Message类,它有三个属性Content、Type和UniqueId。当创建Message对象时,Content和Type是已知的,因此我可以将它们传递给类的构造函数,并将Content和Type属性设置为只读,这样它们的值就不能再更改了。但是,对于UniqueId,我需要在创建对象之后在代码中计算它,并将值赋给UniqueId属性。由于我不能将UniqueId传递给构造函数并使该属性为只读,我想知道是否有这样一种方法,一旦设置了UniqueId属性,它的值就不能再更改了?

public class Message
{
    private readonly string content;
    private readonly AuditMessageType type;
    private Guid messageUId;
    public Message(string syslogMessage, AuditMessageType messageType, Guid messageUniqueId = new Guid())
    {
        content = syslogMessage;
        type = messageType;
        messageUId = messageUniqueId;
    }
    public string Message
    {
        get { return message; }
    }
    public AuditMessageType Type
    {
        get { return type; }
    }
    public Guid MesageUniqueId
    {
        get { return messageUId; }
        set { messageUId = value; } // How to make UniqueId property set once here? It cannot be pass in the constructor, as it needs to computed in the code after the object has been created. 
    }
}

如何使属性设置一次且不能更改

你不能简单地创建一个保护旗吗?

bool wasSetMessageId = false;
public Guid MesageUniqueId
{
    get { return messageUId; }
    set 
    {
       if (!wasSetMessageId) 
       {
          messageUId = value;
          wasSetMessageId = true;
       } 
       else
       {
          throw new InvalidOperationException("Message id can be assigned only once");
       }
    } 
}

方法:

如果Guid.Empty无效,MessageUniqueId的状态

  public Guid MesageUniqueId
    {
        get { return messageUId; }
        set {
             if (messageUId  == Guid.Empty) 
                messageUId = value; 
        } 
    }

如果可以用Nullable Guid代替Guid

 public Guid ? MesageUniqueId
        {
            get { return messageUId; }
            set {
                 if (messageUId  == null) 
                    messageUId = value; 
            } 
        }

如果你不能做到以上两点,使用私有变量:

  private bool messageUniqueIdhasBeenSet = false ; 
 public Guid  MesageUniqueId
        {
            get { return messageUId; }
            set {
                 if (!messageUniqueIdhasBeenSet ) 
                  {
                    messageUId = value;
                    messageUniqueIdhasBeenSet = true ; 
                   } 
            } 
        }
private bool idHasBeenSet = false;
public Guid MessageUniqueId
{
    get { return messageUId; }
    set {
        if (idHasBeenSet) return; //or throw an exception if you need to
        messageUId = value;
        idHasBeenSet = true;
    }
}

c#中没有这样的直接功能,但您可以自己编写,如下所示:-

private Guid? messageUId;
 public Guid MesageUniqueId
    {
        get { return messageUId; }
        set {   
              if (null == messageUId ) 
              { 
                   messageUId = value;              
              }
              else  
              { 
                  throw new InvalidOperationException("Message id can be assigned only once");
              }
     }
    }