protected vs public constructor for abstract class? Is there a difference?

后端 未结 3 751
北荒
北荒 2020-12-14 06:26

This question is out of curiosity. Is there a difference between:

public abstract class MyClass
{
    public MyClass()
    {
    }
}

and

相关标签:
3条回答
  • 2020-12-14 06:55

    In terms of future use of this code, there is no difference.

    0 讨论(0)
  • 2020-12-14 07:02

    They are the same for all practical purposes.

    But since you asked for differences, one difference I can think of is if you are searching for the class's constructor using reflection, then the BindingFlags that match will be different.

    BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
    var constructor = typeof(MyClass).GetConstructor(flags, null, new Type[0], null);
    

    This will find the constructor in one case, but not the other.

    0 讨论(0)
  • 2020-12-14 07:06

    You shouldn't have a public constructor in an Abstract class Constructors on abstract types can only be called by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type with a public constructor is incorrectly designed.

    have a look here for details http://msdn.microsoft.com/en-us/library/ms182126.aspx

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