类System.Dynamic.DynamicObject ..为什么不抽象?

时间:2015-06-10 11:31:29

标签: c# .net

浏览类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()
    {
    }
}

2 个答案:

答案 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>