问题
I am getting an error code in the result. code below. I am basically trying to get a data set from SingleColumn
method and use it in SMA
method. But I am getting results deos not exist in current context.
static public void SMA()
{
double[] closePrice = results.ToArray();
Below you can see the SingleColumn
and part of SMA
code.
#region Single Column
//static public double results;
static public void SingleColumn(IEnumerable<string> strs, int highNum)
{
#region spilt data to columns
Console.WriteLine("Single Column Query:");
var columnQuery = from line in strs
let elements = line.Split(',')
select Convert.ToDouble(elements[highNum]);
var results = columnQuery.ToList();
double[] closePrice = results.ToArray();
#endregion
#region max, min, avg
double average = results.Average();
double max = results.Max();
double min = results.Min();
Console.WriteLine("High: {0}: Low: {1}: Average: {2:0.00}", max, min, average);
#endregion
}
#region Strategy Code SMA
static public void SMA()
{
double[] closePrice = results.ToArray();
int TOTAL_PERIODS = closePrice.Length;
double[] output = new double[TOTAL_PERIODS];
int begin;
int length;
for (int i = 0; i < closePrice.Length-TOTAL_PERIODS; i++) //had to change from -1 to -TOTAL_PERIODS
{
closePrice[i] = (double)i;
}
TicTacTec.TA.Library.Core.RetCode retCode = Core.Sma(0, closePrice.Length-1, closePrice, PERIODS_AVERAGE, out begin, out length, output);
回答1:
You have some options:
- have
SingleColumn
returnresults
and add that as a parameter toSMA
- make
results
a field of the class so it is shared.
Option 1. is cleaner since it forces callers to call SingleColumn
first (or come up with a list on their own)
static public double[] SingleColumn(IEnumerable<string> strs, int highNum)
{
...
return closePrice;
}
#region Strategy Code SMA
static public void SMA(double[] closePrice)
{
int TOTAL_PERIODS = closePrice.Length;
double[] output = new double[TOTAL_PERIODS];
...
}
Note that I changed your output/input from result
to closePrice
since it was just converting it to a List and back. It's cleaner just to leave it as a double[]
. You can also clean up the code a bit by just using ToArray
instead of using ToList
and then ToArray
.
回答2:
You should use static variable.
private static IEnumerable<double> result;
and then in method SingleColumn asign columnQuery.ToList() to this variable
回答3:
Each variable in C# is exists within a scope which is defined by curly braces. In your case the variable result is within the scope SingleCloumn.
public static void SingleColumn(IEnumerable<string> strs, int highNum)
{
}
To use result in another scope, you can make "result" as a global variable. As I can see you have commented out
//static public double results;
first un-comment it and remove var from
var results = columnQuery.ToList();
Hope this helps.
来源:https://stackoverflow.com/questions/28479524/c-sharp-passing-values-from-one-method-to-another