[英]Add extension methods to specific instantiations of unknown class that implements a known interface
I am using a library called SpreadsheetGear. 我正在使用一个名为SpreadsheetGear的库。 With this I work with "IWorkbook" objects that I initialize by a method SpreadsheetGear.Factory.GetWorkbook() whose contract returns an IWorkbook. 这样,我就可以使用SpreadsheetGear.Factory.GetWorkbook()方法初始化的“ IWorkbook”对象,该对象的合同返回一个IWorkbook。
I want to
derive
implement an interface and write extension methods, for example I define 我想
派生
实现接口并编写扩展方法,例如我定义
public partial interface IClientWorkbook : IWorkbook
so I can do something like 所以我可以做类似的事情
IClientWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook;
workbook.ChangeClientName("NewName");
and define the ChangeClientName method somewhere else, but not have it available to IWorkbooks that aren't IClientWorkbook. 并在其他位置定义ChangeClientName方法,但不适用于不是IClientWorkbook的IWorkbook。
I'm not sure how to approach this as can't see the actual class that the GetWorkbook() method returns. 我不确定如何处理此方法,因为看不到GetWorkbook()方法返回的实际类。 Hopefully the question makes sense. 希望这个问题有意义。
As I understand your question, you want to define a custom interface (IClientWorkbook) that you then want to be implemented by objects returned from a 3rd-party API. 据我所知,您想定义一个自定义接口(IClientWorkbook),然后由第3方API返回的对象实现该接口。 You cannot do this. 你不可以做这个。 You can implement extension methods for the existing class or interface, but you cannot add a new interface to an existing class without editing the code for that class. 您可以为现有的类或接口实现扩展方法,但是如果不编辑该类的代码,则无法向现有的类添加新接口。 Also, you cannot create an extension method that doesn't apply to all instances of the extended type. 另外,您不能创建不适用于扩展类型的所有实例的扩展方法。 That is, you cannot create an extension method that only applies to some IWorkbook instances -- you either don't have an extension method, or you have an extension method that applies to all IWorkbook instances. 也就是说,您不能创建仅适用于某些IWorkbook实例的扩展方法-您没有扩展方法,或者您具有适用于所有IWorkbook实例的扩展方法。
You could write wrapper classes for all the bits of the 3rd-party API, and you can then implement your classes however you choose. 您可以为第三方API的所有位编写包装器类,然后可以按自己的选择实现类。 This is sometimes worth it, but more often not. 有时值得,但通常不值得。
It must be as easy as 它必须像
public static class ClientWorkbookExtensions {
public static void ChangeClientName(this IClientWorkbook workbook, String newName) {
workbook.Name = newName; // Or any other code you like
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.