Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

c# - Inherit an abstract class without any constructor

I want to inherit a class from another class, marked as abstract, that not have any constructor defined.

This is my code:

// In one assembly (TheMessage.dll), as seen via F12 in VS (from Metadata)
namespace Namespace1 
{
    public abstract class Message
    {
       public string Body { get; set; }
       // some abstract methods here, not shown.
    }
}

// In another assembly (TheUser.dll)
namespace Namespace2
{
    public class MyMessage : Namespace1.Message
    {
         public MyMessage()
         {
         }
    }
}

The problem is that on the public MyMessage() constructor I get the error

The type 'Namespace1.Message' has no constructors defined

I saw on MSDN site (abstract (C# Reference) first example) that inheriting an abstract class without constructor is possible. So, anyone know why I get this error?

Note that one can inherit just fine when type is in the same DLL as the Message class and it works as that assembly exposes some other types deriving from Namespace1.Message similar to following:

// The same assembly  as Message (TheMessage.dll), as seen via F12 in VS (from Metadata)
namespace Namespace3
{
    public class Message : Namespace1.Message
    {
        public Message() {}
        public Message(string to) {}
    }
}

I've also checked The type '...' has no constructors defined, but it does not speak about inheritance but rather just new-ing up an instance and I clearly have no expectations to directly instantiate an instance of an abstract class.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You probably have an internal constructor (not shown in the code that you posted) and are trying to instantiate the class with the internal constructor from a different assembly.

(The default constructor for a base class is automatically called from a derived class if you don't explicitly specify a base class constructor to call, so it might not be obvious to you that the base class constructor is being called.)

For example, if one assembly contains this class (inside namespace ClassLibrary1):

public class Base
{
    internal Base()
    {
    }
}

And a DIFFERENT assembly does this:

class Derived: Base
{
    public Derived()
    {
    }
}

You will see the following compile error:

The type 'ClassLibrary1.Base' has no constructors defined


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...