开发者

Inheriting class and call hidden base constructor

Consider in AssemblyOne

public class A
{
    internal A (string s)
    { }
}

p开发者_开发知识库ublic class B : A
{
    internal B (string s) : base(s)
    { }
}

In AssemblyTwo

public class C : B
{
    // Can't do this - ctor in B is inaccessible
    public C (string s) : base(s)
}

Obviously this is a code smell, but regardless of if being a bad idea is it possible to call the ctor of B from the ctor of C without changing AssemblyOne?


Ignore Assembly Two for the moment. You would not be able to instantiate an instance of class C, because it inherits from B, which there are no public constructors for.

So if you remove the inheritance issue from Class C, you'd still have an issue creating instances of class B outside of B's assembly due to protection levels. You could use reflection to create instances of B, though.

For the purposes of testing, I altered your classes as follows:

public class A
{
    internal A(string s)
    {
        PropSetByConstructor = s;
    }

    public string PropSetByConstructor { get; set; }
}

public class B : A
{
    internal B(string s)
        : base(s)
    {
        PropSetByConstructor = "Set by B:" + s;
    }
}

I then wrote a console app to test:

static void Main(string[] args)
    {
       System.Reflection.ConstructorInfo ci = typeof(B).GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)[0];
        B B_Object = (B)ci.Invoke(new object[]{"is reflection evil?"});

        Console.WriteLine(B_Object.PropSetByConstructor);


        Console.ReadLine();
    }

I would not recommend doing this, its just bad practice. I suppose in all things there are exceptions, and the exception here is possibly having to deal with a 3rd party library that you can't extend. This would give you a way to instantiate and debug, if not inherit.


This is not possible, even with reflection.

If a class has no accessible constructors, there is no way to create a class that inherits it.


No, you must change AssemblyOne.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜