简体   繁体   English

c#实现接口的类中的虚方法

[英]c# virtual methods in class that implements interface

Lets say I have the following class: 可以说我有以下课程:

namespace myNamespace
{
    [TypeLibType((short)2)]
    [ClassInterface((short)0)]
    [ComImport]
    public class myClass : myInterface
    {
        public virtual void myMethod();
    }
}

and lets say I have the following interface which that class implements 并且假设我有该类实现的以下接口

namespace myNamespace
{
    [Guid("2105896C-2B38-4031-BD0B-7A9C4A39FB93")]
    [TypeLibType((short)4160)]
    [ComImport]
    public interface myInterface
    {
        void myMethod();
    }
}

Now, when I compile this the virtual method in the first class comes back with the following error: 现在,当我编译它时,第一个类中的虚方法返回时出现以下错误:

'myNamespace.myClass.myMethod()' must declare a body because it is not marked abstract, extern, or partial

This method should compile just fine because it is marked as virtual, but for some reason it still will not compile and I'm kind of at a loss as to why because if I alternatively define a body on MyMethod in MyClass then I get the following error instead: 这个方法应该编译得很好,因为它被标记为虚拟,但由于某种原因它仍然不会编译,我有点不知道为什么因为如果我在MyClass中的MyMethod上定义一个主体然后我得到以下错误的是:

Since 'myClass.myMethod' has the ComImport attribute, 'myNamespace.myClass.myMethod' must be extern or abstract

I'm using .Net 3.5 for this setup, but it still doesn't work in .Net 4.0 either 我正在使用.Net 3.5进行此设置,但它仍然无法在.Net 4.0中运行

I think you are confusing virtual with abstract . 我认为你将virtualabstract混淆。 Virtual methods require an implemenation, but may be overridden. 虚方法需要实现,但可能会被覆盖。

Abstract methods on the other hand can be declared as you have it without an implementation. 另一方面,抽象方法可以在没有实现的情况下声明。 Subclasses then bear the responsibility of providing the implementation, and if they don't they are greeted with a compiler error. 然后子类承担提供实现的责任,如果不是,则会遇到编译器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM