浏览类System.Dynamic.DynamicObject,我发现它是具体的(非抽象的)类,但是阻止通过创建默认构造函数protected
来直接创建它的实例。
那么使用public
构造函数不能使它成为抽象的重点是什么?
澄清:
class Base1
{
protected Base1() // protected constructor, concrete class
{
}
}
class Derived1 : Base1
{
public Derived1() : base()
{
}
}
abstract class Base2
{
public Base2() // public constructor, abstract class
{
}
}
class Derived2 : Base2
{
public Derived2() : base()
{
}
}
答案 0 :(得分:1)
有一条评论解释
/// <summary>
/// Enables derived types to initialize a new instance of the <see cref="T:System.Dynamic.DynamicObject"/> type.
/// </summary>
[__DynamicallyInvokable]
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
protected DynamicObject()
{
}
它在某处用于创建System.Dynamic.DynamicObject
答案 1 :(得分:1)
使用受保护的构造函数,这是可能的:
public class MyClass
{
protected MyClass() { }
public static MyClass GetInstance()
{
return new MyClass();
}
}
public class MyDerivedClass : MyClass
{
}
public static void Main()
{
var myInstance = MyClass.GetInstance();
var myDerivedInstance = new MyDerivedClass();
var constructor = typeof(MyClass).GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
null,
Type.EmptyTypes,
null);
var instanceFromReflection = (MyClass) constructor.Invoke();
}
抽象MyClass
既不能由MyClass.GetInstance()
(return new MyClass();
处的编译器错误)实例化,也不能由反射类型(运行时错误System.MemberAccessException: Cannot create an instance of MyClass because it is an abstract class.
)实例化< / p>