protected vs public constructor for abstract class

2019-01-22 11:31发布

问题:

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

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

and

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

Thanks.

回答1:

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.



回答2:

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



回答3:

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