我有一个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.
}
}
答案 0 :(得分:5)
难道你不能简单地创建一个警卫旗吗?
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");
}
}
}
答案 1 :(得分:1)
如何做到这一点:
如果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 ;
}
}
}
答案 2 :(得分:0)
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;
}
}
答案 3 :(得分:0)
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");
}
}
}