繁体   English   中英

在 C# 中,只有在没有 class 属性的情况下,我才能生成一个值?

[英]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;
   }
}
  • 是否可以在C#中进行这项工作?
  • 如果是这样,如何

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM