【问题标题】:In C#, how can I generate a value for a class property only if there isn't one?在 C# 中,只有在没有类属性的情况下,如何才能为类属性生成值?
【发布时间】:2020-08-21 17:01:10
【问题描述】:

我有以下 C# 类,其属性为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# 中完成这项工作?
  • 如果是这样,如何

【问题讨论】:

  • 你是对的 - 在 getter 中访问 if (this.Id == null) 会递归调用 getter(因为这就是 this.Id 在后台调用的内容)。解决方案是使用明确定义的支持字段,而不是自动属性。
  • 你有一个堆栈溢出,因为if(this.Id == null) 调用了你已经在其中的Id 属性的getter,导致无限递归。正如下面的答案所述,解决方案是为属性使用显式支持字段。
  • 干杯。给大家寻求解决方案!....我会在 8 分钟内接受@daniel89 的解决方案(只要 StackOverflow 允许我),除非有人有更聪明的答案。 :-)
  • 它回答你的问题了吗? Why does Property Set throw StackOverflow exception? 好像是一模一样
  • @PavelAnikhouski,您对“精确”的定义可以使用一些微调,但它无疑是一个类似的问题。另一方面,该问题涉及一个非常简单的用例,并没有明确说明从访问器中访问您希望设置的属性的任何和所有尝试都同样注定要失败。也许对于习惯于 C# 的人来说应该很明显,但对于 Apex 开发人员来说,这是一种常见的模式,就不是那么明显了。

标签: c# conditional-statements guid getter accessor


【解决方案1】:

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

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;
   }
}

【讨论】:

  • @MikeH id 字段不需要初始化,因为它在创建类的新实例时采用默认值(null)
  • 为解决方案干杯!....我会在 8 分钟内接受这个解决方案(只要 StackOverflow 允许我),除非有人有更聪明的答案。 :-)
【解决方案2】:

你需要做的是不要使用自动属性功能。

您应该明确输入 private string _id; 字段,并且您的 getter 和 setter 应该在内部使用它

【讨论】:

  • 为答案干杯我会接受,但我更喜欢@daniell89 的完整解决方案。
猜你喜欢
  • 2023-01-25
  • 2022-12-03
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多