Difference between revisions of "Zh/Documentation/DevGuide/ProUNO/CLI/The Override Problem"
From Apache OpenOffice Wiki
< Zh | Documentation
m |
|||
Line 7: | Line 7: | ||
|NextPage=Zh/Documentation/DevGuide/ProUNO/CLI/Important Interfaces and Implementations | |NextPage=Zh/Documentation/DevGuide/ProUNO/CLI/Important Interfaces and Implementations | ||
}} | }} | ||
− | + | {{Documentation/DevGuideLanguages|Documentation/DevGuide/ProUNO/CLI/{{SUBPAGENAME}}}} | |
{{DISPLAYTITLE:重载问题}} | {{DISPLAYTITLE:重载问题}} | ||
Revision as of 03:16, 14 May 2009
术语 “override problem” 描述的是由于接口方法重载基类的实现,从而不能存取基对象的虚拟函数
时将会发生的问题。例如,所有 CLI 对象都是由 System.Object
派生的。当接口中方法的签名与 System.Object
的其中一个方法相同时,如果接口方法是虚拟的,则不能存取相应的 System.Object
方法。
例如,请考虑接口 XFoo
的以下声明极其实现类:
using namespace System; public __gc __interface XFoo { public: virtual String* ToString(); }; public __gc class Foo : public XFoo { public: virtual String * ToString() { return NULL; } };
如果调用实例的方法 ToString
,则将调用接口方法的实现。例如:
int main(void) { Foo * f = new Foo(); Object * o = f; f->ToString(); // calls Foo.ToString o->ToString(); // calls Foo.ToString return 0; }
由于接口方法可能具有与 System.Object
的名称不同的语义,因此可能不是有意如此。
解决方案可防止接口方法重载 System.Object
的方法,而无需将接口方法设为非虚拟。CLI 通过 “newslot” 标志提供一种补救措施,可将该标志附加到 IL 代码的方法头中。在使用 “newslot” 表示方法时,CLI 语言可能具有不同的含义。
以下示例说明用不同语言实现 XFoo
的方法,这样仍然可以调用 Object.ToString
。
//C++ //interface methods should be qualified with the interface they belong to public __gc class A: public XFoo { public: virtual String* XFoo::ToString() { Console::WriteLine("A::foo"); return NULL; } };
在 C# 中,提供实现有不同的方法:
// IL contains: newslot final virtual public new string ToString() { }
关键字 new 将 newslot 属性插入到 CLI 方法头中:在继承类中,无法重载此实现。
//IL contains: newslot virtual public new virtual string ToString() { }
在派生类中,可以重载此方法。
// Using a qualified method name for the implementation. The virtual //modifier is not allowed string XFoo.ToString() { return null; }
在派生类中,无法重载此实现。调用方法前,必须先将实现类的实例转换成 XFoo。
'VB .NET Public Shadows Function ToString() As String Implements XFoo.ToString Console.WriteLine("Foo.toString") End Function
在派生类中,无法重载此实现。
Public Overridable Shadows Function ToString() As String _ Implements XFoo.ToString Console.WriteLine("Foo.toString") End Function
可以重载此方法。
Content on this page is licensed under the Public Documentation License (PDL). |