简体   繁体   English

C#在类属性中创建列表

[英]C# create list within class properties

I created the following within my class 我在课堂上创建了以下内容

  private List<CreditCardTransaction> _ccTransactions = new List<CreditCardTransaction>();

  public List<CreditCardTransaction> ccTransactions
  {
      get { return _ccTransactions; }
      set { _ccTransactions = value; }
  }

Within another public function (in the same class) I attempted to add a value to the list using the following code: 在另一个公共函数(在同一类中)中,我尝试使用以下代码将值添加到列表中:

  _ccTransactions.Add(new CreditCardTransaction(Convert.ToString(items[0]), Convert.ToString(items[1]), Convert.ToDouble(items[2]), DateTime.Parse(items[3])));

However a red wavy line under "_ccTransactions" saying 但是在“ _ccTransactions”下面有一条红色的波浪线

Error 1 An object reference is required for the non-static field, method, or property 'CreditCardTransactionKeeper.CreditCardTransaction._ccTransactions' 错误1非静态字段,方法或属性'CreditCardTransactionKeeper.CreditCardTransaction._ccTransactions'需要对象引用

What is the proper way for me to add a new item to the list when I am within a method in the class that defined this list? 当我在定义此列表的类中的方法中时,对我添加新项目的正确方法是什么?

You can't access the non-static field ( _ccTransactions ) inside a static function- by the error, I assume your other function is static. 您无法访问静态函数内的非静态字段( _ccTransactions ),但由于错误,我认为您的其他函数是静态的。

You need to either make _ccTransactions static, make your calling function non-static, or get a reference to an object of that class to access _ccTransactions from. 您需要将_ccTransactions静态,将调用函数_ccTransactions非静态,或者获取对该类对象的引用以从中访问_ccTransactions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM