我有以下内容 C# 带属性的类 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#,这是 不 工作,而是我得到了一个 叠叠乐 (显然不是这个网站).最好的猜测是,在同一个属性的getter中调用this.Id似乎会导致循环逻辑。
在 Salesforce Apex有了这个 类似 编码,它 是否 担任 I 的值为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;
字段,而你的getters和setters应该在内部使用这个