我有以下问题:
在方法1中,我得到一个字符串列表并将其传递给方法
在方法2中,我根据列表生成一个二维数组,并将列表进一步传递给方法3
在方法3中,我将2d数组转换为数据表
现在我想将数据表返回给方法1,但我不知道该怎么做。图为我的问题:
我的代码:
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
Document doc = commandData.Application.ActiveUIDocument.Document;
View activeView = commandData.View;
if(activeView is ViewSchedule)
{
GetDimensions(activeView as ViewSchedule);
}
return Result.Succeeded;
}
public void GetDimensions(ViewSchedule schedule)
{
TableSectionData bodySelection = schedule.GetTableData().GetSectionData(SectionType.Body);
int numberOfRows = bodySelection.NumberOfRows;
int numberOfColumns = bodySelection.NumberOfColumns;
string[,] values = new string[numberOfRows,numberOfColumns];
FillArray(SectionType.Body, bodySelection, numberOfColumns, numberOfRows, values, schedule);
}
public void FillArray(SectionType secType, TableSectionData data,
int numberOfColumns, int numberOfRows, string[,] values, ViewSchedule schedule)
{
for (int r = data.FirstRowNumber; r < numberOfRows; r++)
{
for (int c = data.FirstColumnNumber; c < numberOfColumns; c++)
{
values[r, c] = schedule.GetCellText(secType, r, c);
}
}
}
现在我想将填充的数组返回Execute
。
答案 0 :(得分:2)
直接以这种方式传递它是不可能的。有三种选择:
make方法2获取结果并将其传回:
int Method2()
{
var method3Result = Method3();
return method3Result;
}
void Method1()
{
var result = Method2(); //indirectly gets from Method3
}
提供共享状态:
public class Method3Result { public int Value { get; set; } }
public class X
{
private Method3Result method3Result = new Method3Result();
public void Method1()
{
Method2();
//process result from method3Result
}
public void Method2()
{
Method3();
}
public void Method3()
{
method3Result.Value = 3;
}
}
提供回调:
public void Method1()
{
int method3Result;
Method2(value => method3Result = value);
}
public void Method2(Action<int> callback)
{
Method3(callback);
}
public void Method3(Action<int> callback)
{
callback(3);
}
}
在您的情况下,选项1似乎很简单:
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
Document doc = commandData.Application.ActiveUIDocument.Document;
View activeView = commandData.View;
string[,] values = null;
if (activeView is ViewSchedule)
{
values = GetDimensions(activeView as ViewSchedule);
}
return Result.Succeeded;
}
public string[,] GetDimensions(ViewSchedule schedule)
{
//...
return values;
}
此外,将FillArray
更改为类似CreateArray
并使其返回数组似乎更清晰:
public void FillArray(SectionType secType, TableSectionData data, int numberOfColumns, int numberOfRows, string[,] values, ViewSchedule schedule)
{
string[,] values = new string[numberOfRows,numberOfColumns];
for (int r = data.FirstRowNumber; r < numberOfRows; r++)
{
for (int c = data.FirstColumnNumber; c < numberOfColumns; c++)
{
values[r, c] = schedule.GetCellText(secType, r, c);
}
}
return values;
}
所以它更容易使用。