如何为数组数据成员定义get和set?

Bob*_*Bob 15 c#

我正在创建一个Customer具有以下数据成员和属性的类:

private string customerName;
private double[] totalPurchasesLastThreeDays; //array of 3 elements that will hold the totals of how much the customer purchased for the past three days i.e. element[0] = 100, element[1] = 50, element[2] = 250

public string CustomerName
{
get { return customerName; }
set { customerName = value; }
}

public double[] TotalPurchasesLastThreeDays
{
?
}
Run Code Online (Sandbox Code Playgroud)

如何定义数组数据成员的get和set?

Joe*_*oey 26

你想要一个索引器吗?

public double this[int i] {
  get { return totalPurchasesLastThreeDays[i]; }
  set { totalPurchasesLastThreeDays[i] = value; }
}
Run Code Online (Sandbox Code Playgroud)

因为否则问题听起来有点奇怪,因为你已经在你的代码中实现了一个属性,并且显然能够这样做.

  • 索引器没有名称,因为您直接索引对象.所以你应该删除`Purchases`来编译你的代码.事实上,索引器的工作方式如下:`myCustomer [index]`,而不是这样:`myCustomer.Purchases [index]` (4认同)

Jas*_*ans 11

您可以使用自动属性:

public class Customer
{
    public string CustomerName { get; set; }

    public double[] TotalPurchasesLastThreeDays { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

或者如果你想:

public class Customer
    {
        private double[] totalPurchasesLastThreeDays; 

        public string CustomerName { get; set; }

        public double[] TotalPurchasesLastThreeDays
        {
            get
            {
                return totalPurchasesLastThreeDays;
            }
            set
            {
                totalPurchasesLastThreeDays = value;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后在构造函数中,您可以设置一些默认值:

public Customer()
{
    totalPurchasesLastThreeDays = new double[] { 100, 50, 250 };
}
Run Code Online (Sandbox Code Playgroud)