在 C# 中,如何仅在没有类属性的情况下为类属性生成值?

Bri*_*ler 2 c# getter guid accessor conditional-statements

我有以下带有属性的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;
   }
}
Run Code Online (Sandbox Code Playgroud)

C#中,这样做不是工作,而是我得到一个计算器(不是这个网站,很明显)。最好的猜测是,在同一属性的 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;
   }
}
Run Code Online (Sandbox Code Playgroud)
  • 是否可以在C# 中完成这项工作?
  • 如果是这样,如何

dan*_*l89 6

可能您应该使用私有字段创建完整的属性。

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;
   }
}
Run Code Online (Sandbox Code Playgroud)