C# Interop Non-invocable member 'Microsoft.Office.Interop.Excel.Range.End' cannot be used like a method

五迷三道 提交于 2019-12-12 16:23:50

问题


I'm using C# Interop to get some values from a Worksheet and I get the following error:

Non-invocable member 'Microsoft.Office.Interop.Excel.Range.End' cannot be used like a method.

This is my code:

var wb = (Excel.Workbook)Globals.ThisAddIn.Application.ActiveWorkbook;
var wsEvars = wb.Sheets["Evars"];
var wsProps = wb.Sheets["Props"];
var wsEvents = wb.Sheets["Events"];
var wsListVars = wb.Sheets["List Vars"];

var sheetList = new Excel.Worksheet[] { wsEvars, wsProps, wsEvents, wsListVars };

for (var i = 0; i < sheetList.Length; i++)
{
    // I get the error on the line below
    var rowLast = sheetList[i].Range["I" + sheetList[i].Rows.Count].End(Excel.XlDirection.xlUp).Row;
}

The thing is that is works if I try as follows:

for (var i = 0; i < sheetList.Length; i++)
{
    var rowLast = wsEvars .Range["I" + wsEvars .Rows.Count].End(Excel.XlDirection.xlUp).Row;
}

Am I missing something?


回答1:


Looks like you found a bug in the C# compiler. The bug is actually present in the workaround, it ought to not compile for the same reasons the first snippet did not. Albeit that it is difficult to definitely claim that this is a bug, the C# language spec does not describe what is acceptable in this case.

The Range.End property is an indexed property. Such properties are not formally supported in C#, the language permits only the class indexer (aka this[]) to be the one-and-only indexed property of a class. But that restriction was lifted in C# version 4, specifically to make interop with COM servers easier. Like Excel, indexed properties are very common in COM object models.

Like the normal indexer, you have to use square brackets. Fix:

    var rowLast = sheetList[i].Range["I" + sheetList[i].Rows.Count]
                              .End[Excel.XlDirection.xlUp].Row;

And the workaround you had to use in older C# versions is still available:

    var rowLast = sheetList[i].Range["I" + sheetList[i].Rows.Count]
                              .get_End(Excel.XlDirection.xlUp).Row;

Hard to guess why it finds () parentheses acceptable in the second snippet. It looks like a bug, swims like a bug and quacks like a bug, so it is probably a bug. Let them know about it by clicking the New Issue button. I doubt they'll fix it but there might be more wrong than meets the eye.



来源:https://stackoverflow.com/questions/43317699/c-sharp-interop-non-invocable-member-microsoft-office-interop-excel-range-end

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!