[英]In C#, how can I generate a value for a class property only if there isn't one?
我有以下C# class 的屬性Id
,我想用 GUID 設置它並返回,如果消費者調用 myClass.Id 的實例的值,該值尚未設置,否則保留並返回現有的價值。
public class IdentifiableClass{
public string Id {
get {
if (this.Id == null) {
this.Id = Guid.NewGuid().ToString();
Console.WriteLine("########## Id : " + this.Id );
}
return this.Id;
}
set => this.Id = value;
}
}
在C#中,這不起作用,而是我得到了一個stackoverflow (顯然不是這個站點)。 最好的猜測是,在同一個屬性的 getter 中調用 this.Id 似乎會導致循環邏輯。
在Salesforce Apex中,使用類似的代碼,它確實可以按我的預期工作,將 this.Id 的值評估為 null,將值分配給新的 Guid,顯示值,然后返回值:
public class IdentifiableClass {
public string Id {
get {
if (this.Id == null) {
this.Id = String.valueOf(Integer.valueof((Math.random() * 10)));
System.debug('########## Id : ' + this.Id );
}
return this.Id;
}
set;
}
}
可能您應該使用私有字段創建完整的屬性。
public class IdentifiableClass{
private string id;
public string Id {
get {
if (this.id == null) {
this.id = Guid.NewGuid().ToString();
Console.WriteLine("########## Id : " + this.id );
}
return this.id;
}
set => this.id = value;
}
}
您需要做的是不要使用自動屬性功能。
你應該明確地把private string _id;
字段,你的 getter 和 setter 應該在內部使用它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.