简体   繁体   中英

Creating a List<T>, issues with formatting

I'm getting all sorts of compile errors from the code below. I'm not quite sure how to Add items to a List when I have a List setups as shown below. I wan't to basically maintain the values set within the StockEntry class, and use the class StockItem as a Count. Using... _stocks.Value.Count++

public class StockEntry
{
  public string Name;
  public PeriodType Period;
  public int Min;


  public StockEntry(string Name, PeriodType Period, int Min)
  {
    this.Name = Name;
    this.Period = Period;
    this.Min = Min;
  }
}

public class StockItem<T>
{
  public T Value;

  public StockItem() {} 
  public StockItem(T val) {Value = val;}    
}

 List<StockItem<StockEntry>> _stocks = new List<StockItem<StockEntry>>();

 protected override void Initialize()
 {                                  
  _stocks.Add(new StockItem(StockEntry("ABC", PeriodType.Minute, 5)));          
  _stocks.Add(new StockItem(StockEntry("ACE", PeriodType.Minute, 5)));
  _stocks.Add(new StockItem(StockEntry("ACN", PeriodType.Minute, 5)));
 }

Aside from anything else, this could be the problem:

_stocks.Add(new StockItem(StockEntry("ABC", PeriodType.Minute, 5)));  

(and the similar lines).

StockItem is a generic class, so you need to specify the type argument:

_stocks.Add(new StockItem<StockEntry>(StockEntry("ABC", PeriodType.Minute, 5)));

If you want to avoid that somewhat redundant specification, you could create a static generic method in a non-generic type:

// Overload StockItem<T> by generic arity
public static class StockItem
{
    public static StockItem<T> Of(T item)
    {
        return new StockItem<T>(item);
    }
}

Then:

_stocks.Add(StockItem.Of(StockEntry("ABC", PeriodType.Minute, 5)));

That said, it's not really clear why StockItem needs to be generic in the first place. And I'd definitely avoid using a public field - at least make it an automatically implemented property. (Ideally IMO, make it a readonly property backed by a readonly field set in the constructor, and remove the parameterless constructor. But then I'm a fan of immutability.) Likewise I'd get rid of the public fields in StockEntry .

I think if you add new keyword to this line:

_stocks.Add(new StockItem(StockEntry("ABC", PeriodType.Minute, 5)));

your problem will be resolve.

_stocks.Add(new StockItem(new StockEntry("ABC", PeriodType.Minute, 5)));

_stocks and Initialize need to be part of a class - they are not currently.

Presumably you want them as part of StockItem:

public class StockItem<T>
{
  public T Value;

public StockItem() {} 
public StockItem(T val) {Value = val;}  
} // The class StockItem ends with this bracket

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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