protected vs public constructor for abstract class

2019-01-22 11:12发布

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.

3条回答
男人必须洒脱
2楼-- · 2019-01-22 11:55

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

查看更多
在下西门庆
3楼-- · 2019-01-22 12:00

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

查看更多
闹够了就滚
4楼-- · 2019-01-22 12:03

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.

查看更多
登录 后发表回答