When I'm writing code in the partial class file for a worksheet (Sheet8, for instance), how do I pass "this" class as an argument expecting objects with the Microsoft.Office.Interop.Excel.Worksheet interface?
Here's an example of from the Sheet8.cs file:
public partial class Sheet8
{
private void Sheet8_startup(object sender, System.EventArgs e)
{
var object = new MyCustomClass(this);
}
}
And the consuming code that I'd like to write:
class MyCustomClass
{
public MyCustomClass(Microsoft.Office.Interop.Excel.Worksheet sheet)
{
// Do something with the sheet
}
}
The problem seems to be that "this" always refers to the Sheet n object, and cannot be cast to the interface type necessary for creating loosely-coupled interfaces with custom code. Any suggestions?
After weeks of searching, I figured it out. It's actually embarrassingly simple.
Each Globals.SheetN
object has an InnerObject() method that returns an object with the right interface. An example of how to use it:
public partial class Sheet8
{
Sheet8_startup(object sender, System.EventArgs e)
{
var sheet = new MyCustomClass(InnerObject());
}
}
From there, you can build loosely-coupled, custom objects to your heart's content!
You can also use the this
keyword instead of InnerObject()
.
public partial class Sheet8
{
Sheet8_startup(object sender, System.EventArgs e)
{
var sheet = new MyCustomClass(this);
}
}
Then, for the constructor of your consuming class use the Microsoft.Office.Tools.Excel.WorksheetBase
type (instead of the Worksheet
type).
class MyCustomClass
{
public MyCustomClass(Microsoft.Office.Interop.Excel.WorksheetBase sheet)
{
// Do something with the sheet
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.