简体   繁体   中英

Inheriting class and call hidden base constructor

Consider in AssemblyOne

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

public 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.

不,您必须更改AssemblyOne。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM