简体   繁体   中英

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:

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

I think you are confusing virtual with abstract . 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.

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.

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