C# 转到 class 的确切实例
C# Go to exact instance of class
我的 ExcelHandler 有问题 class:
...
class ExcelHandler
{
static Excel.Application xlApp;
static Excel.Workbook xlWorkBook;
static Excel.Worksheet xlWorkSheet;
static object misValue = System.Reflection.Missing.Value;
static string _filename;
public ExcelHandler(string filename)
{
openExcel(_filename);
}
internal static bool openExcel(string filename)
{
_filename = filename;
... other code ...
internal Array GetRange(string range)
{
Array xlValues;
string[] rangeSplit = range.Split(':');
Excel.Range xlRange = xlWorkSheet.get_Range(rangeSplit[0], rangeSplit[1]);
xlValues = (Array)xlRange.Cells.Value;
return xlValues;
}
... other code ...
如果我在我的代码中以以下方式访问 Excel 个文件:
ExcelHandler eh01 = new ExcelHandler(file01); // file for write to
for (blahblah) { // 1 to 5
ExcelHandler eh02 = new ExcelHandler(file02);
Array licLoad = eh02.GetRange("C5:CB5");
eh02.closeExcel();
foreach (blahbla) // 26 values
{
eh01.insertCell(f.ToString(), row++, 3);
}
}
eh01.closeExcel();
eh02.GetRange returns 来自 file01 而不是 file02 的数据,我真的迷路了,为什么?你有什么建议吗?
Groo 的评论是准确的。创建静态属性会使 class 的所有实例共享它的值。静态属性属于类型本身,而不属于对象。
来自微软文档:
Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object.
我的 ExcelHandler 有问题 class:
...
class ExcelHandler
{
static Excel.Application xlApp;
static Excel.Workbook xlWorkBook;
static Excel.Worksheet xlWorkSheet;
static object misValue = System.Reflection.Missing.Value;
static string _filename;
public ExcelHandler(string filename)
{
openExcel(_filename);
}
internal static bool openExcel(string filename)
{
_filename = filename;
... other code ...
internal Array GetRange(string range)
{
Array xlValues;
string[] rangeSplit = range.Split(':');
Excel.Range xlRange = xlWorkSheet.get_Range(rangeSplit[0], rangeSplit[1]);
xlValues = (Array)xlRange.Cells.Value;
return xlValues;
}
... other code ...
如果我在我的代码中以以下方式访问 Excel 个文件:
ExcelHandler eh01 = new ExcelHandler(file01); // file for write to
for (blahblah) { // 1 to 5
ExcelHandler eh02 = new ExcelHandler(file02);
Array licLoad = eh02.GetRange("C5:CB5");
eh02.closeExcel();
foreach (blahbla) // 26 values
{
eh01.insertCell(f.ToString(), row++, 3);
}
}
eh01.closeExcel();
eh02.GetRange returns 来自 file01 而不是 file02 的数据,我真的迷路了,为什么?你有什么建议吗?
Groo 的评论是准确的。创建静态属性会使 class 的所有实例共享它的值。静态属性属于类型本身,而不属于对象。
来自微软文档:
Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object.