实现只读

时间:2017-05-18 06:36:29

标签: c#

我必须为我的Description字段实现只读,我只有一个get语句。当我试图写入数组列表描述时,它不会让我拥有,因为它是我唯一的吸气剂。如下所示,试图在我的主要做。

我尝试编写构造函数但在尝试添加到数组列表时获取错误消息获取方法组。

static void Main(string[] args)

 grocery.Add(new GroceryItem { Description="4L Milk" Price = 3.87M, ExpirationDate= DateTime.Now });

Class Grocerypackage
 public string Description
        {
            get { return description; }
        }

1 个答案:

答案 0 :(得分:1)

namespace ConsoleApplication7
{
    internal class Program
    {
        private static void Main()
        {
            var groceries = new List<GroceryItem>();
            groceries.Add(new GroceryItem("Carrot", 23.57m, DateTime.Today));
        }
    }

    internal sealed class GroceryItem
    {
        public GroceryItem(string description, decimal price, DateTime expirationDate)
        {
            Description = description;
            Price = price;
            ExpirationDate = expirationDate;
        }
        public string Description { get; }
        public decimal Price { get; }
        public DateTime ExpirationDate { get; }
    }
}

在C#中,您可以初始化构造函数中的只读字段。您也可以使用private set。然后GroceryItem类可以访问setter。 e.g。

internal class Program
    {
        private static void Main()
        {
            var gi = new GroceryItem("Carrot");
            gi.Foo();

            Console.WriteLine(gi.Description);
        }
    }

    internal class GroceryItem
    {
        public GroceryItem(string description)
        {
            Description = description;   // We can set this in ctor
        }
        public string Description { get; private set; }

        public void Foo()
        {
            Description = "Foo";
        }
    }

您还可以使用带有readonly关键字的支持字段

internal class GroceryItem
    {
        private readonly string _description;
        public GroceryItem(string description)
        {
            _description = description;   // We can set this in ctor
        }
        public string Description
        {
            get { return _description; }
        }
    }