C#如何在属性的设置器内部获取逻辑并将其分配给属性?

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

我有一个属性,其中包含一个带有内部逻辑的Setter(以为Id生成随机字符串)。

public class Customer
{
  private string _customerId;

  public string  CustomerId
  {
      get { return _customerId; }
      private set { _customerId = Utilities.RandomString(6); }
  }
  public string CustomerName { get; set; }
}

但是我如何从另一个类中调用此属性,以实际触发设置器内部的逻辑?

class Program
{
  static void Main(string[] arg)
  {
    var customer = new Customer();
    customer.CustomerName = "John";
    customer.CustomerId = ?????
  }
}

或者我是否使事情过于复杂,不应该在此属性内使用此逻辑?

c#
2个回答
2
投票

您应该从设置器中删除private修饰符,以便能够从Customer类的外部设置该属性的值。

但是,查看您的代码,似乎不需要setter中的逻辑。相反,您可以在构造函数中分配随机的客户ID。


0
投票

您的属性设置器被声明为private,因此您将无法从另一个类对其进行分配。从属性中删除private访问器,然后就可以分配想要的值了,因为您没有在设置器中使用value。因此如下所示:

customer.CustomerId = "any-string-here";

话虽如此,我认为这不是实现所需结果的最佳方法。一种可能的替代方法是在首次检索属性值时生成随机ID。然后,您可以完全取消安装员。建议的解决方案:

public class Customer
{
  private string _customerId;

  public string  CustomerId
  {
      get
      {
        if (string.IsNullOrWhiteSpace(_customerId))
            _customerId = Utilities.RandomString(6);

        return _customerId;
      }
  }
  public string CustomerName { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.