Whats the utility of public constructors in abstract classes in C#?

前端 未结 3 1287
不思量自难忘°
不思量自难忘° 2020-12-15 17:29

If a public constructor in an abstract class can only be called by their derived classes it should be functionally equivalent to a protected constructor. Right?

Is t

相关标签:
3条回答
  • 2020-12-15 17:37

    You are correct. A public constructor in an abstract class is functionally equivalent to a protected constructor.

    I prefer to use a protected constructor in this case.

    While, it is true that the compiler will not complain about you doing this, the compiler will complain about trying to generate an instance of the abstract class. Visual Studio is smart enough, as well, to not provide Intellisense if you try to instantiate the abstract class.

    0 讨论(0)
  • 2020-12-15 17:37

    Yes, you are right, practically public constructor has no use in abscract class as you cant create them.

    However compiler will not complain because that way there are so many useless things you can write in context of c#, but it will not be able to check its logical meaning, it can only check the parsing rules which it is set for.

    And sure c# creators have focused on creating compilation grammar (rules) that are actual harmful and violating the language use.

    0 讨论(0)
  • 2020-12-15 17:44

    Absolutely correct. You should favor the protected constructor.

    EDIT: no the compiler doesn't complain, but tools like FxCop (& Code Analysis) do. I believe there are some weird reflection tricks you can do with public constructors on abstract classes, but from a standpoint where you are merely providing base class functionality to other developers writing subclasses, stick with the protected constructor.

    0 讨论(0)
提交回复
热议问题