在C#中,如果没有类属性,我如何才能为其生成一个值?

问题描述 投票:0回答:1

我有以下内容 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;
   }
}
  • 有没有可能让这个工作在 C#?
  • 如果是的话 如何?
c# conditional-statements guid getter accessor
1个回答
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;
   }
}

4
投票

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

你应该明确地把 private string _id; 字段,而你的getters和setters应该在内部使用这个

© www.soinside.com 2019 - 2024. All rights reserved.