将变量声明为类的字段

时间:2013-09-19 02:27:55

标签: c# class field

使用C# 这是一个我敢肯定的基本问题。我收到错误..“当前上下文中不存在名称'_stocks'”。我知道这是因为我在Initialize方法中声明了_stocks字典。这使_stocks变量成为局部变量,并且只能在Initialize方法中访问。我需要将_stocks变量声明为类的一个字段(因此可以通过该类的任何方法访问它)。您将在下面看到的另一种方法是OnBarUpdate()。我如何将_stocks变量声明为类的一个字段?

public class MAcrossLong : Strategy
{
    //Variables
    private int variable1 = 0
    private int variable2 = 0

    public struct StockEntry
    {
        public string Name { get; set; }
        public PeriodType Period { get; set; }
        public int Value { get; set; }
        public int Count { get; set; }
    }

    protected override void Initialize()
    {                       
        Dictionary<string, StockEntry> _stocks = new Dictionary<string, StockEntry>();

        _stocks.Add("ABC", new StockEntry { Name = "ABC", Period = PeriodType.Minute, Value = 5, Count = 0 } );
    }

    protected override void OnBarUpdate()
    {
       //_stocks dictionary is used within the code in this method.  error is occurring         within this method
    }
}

* *添加了部分....

我应该只是在OnBarUpdate()中发布代码,因为我现在得到其他错误...... 'System.Collections.Generic.Dictionary.this [string]'的最佳重载方法匹配有一些无效的参数 参数'1':无法从'int'转换为'string' 运营商'&lt;'不能应用于'NinjaTrader.Strategy.MAcrossLong.StockEntry'和'int'

类型的操作数
protected override void OnBarUpdate()

        {  //for loop to iterate each instrument through
for (int series = 0; series < 5; series++)
if (BarsInProgress == series)
{  
var singleStockCount = _stocks[series];
bool enterTrade = false;
   if (singleStockCount < 1)
{
enterTrade = true;
}
else
{
enterTrade = BarsSinceEntry(series, "", 0) > 2; 
} 

                if (enterTrade)
 {  // Condition for Long Entry here


                  EnterLong(200);
{
 if(_stocks.ContainsKey(series))
{
_stocks[series]++;
}
}
 }
            } 
}

2 个答案:

答案 0 :(得分:0)

与宣布variable1variable2 ....

的方式相同
public class MAcrossLong : Strategy
{
   private int variable1 = 0;
   private int variable2 = 0;
   private Dictionary<string, StockEntry> _stocks;

   protected override void Initialize()
   {
      _stocks.Add("ABC", new StockEntry { Name = "ABC", Period = PeriodType.Minute, Value = 5, Count = 0 } );
   }

   protected override void OnBarUpdate()
   {
      _stocks["ABC"].Name = "new name"; // Or some other code with _stocks
   }
}

要修复最近添加的OnBarUpdate()内的错误,您需要切换到foreach循环并使用KeyValuePair<string, StockEntry>迭代器。您可以详细了解hereherehere

看起来应该是这样的:

foreach(KeyValuePair<string, StockEntry> stock in _stocks)
{
   string ticker = stock.Key;
   StockEntry stockEntry = stock.Value;
   // Or some other actions with stock
}

答案 1 :(得分:0)

您需要在类级别范围内声明_stocks。由于您已在Initialize方法中声明了它,因此它的可见性变为该方法的本地。因此,您应该将其与variable1variable2一起声明为

private int variable1 = 0;
private int variable2 = 0;
private Dictionary<string, StockEntry> _stocks;

您可能需要查看Access modifiersVariable and Method Scopes以便更好地理解