简体   繁体   English

继承类并调用隐藏的基础构造函数

[英]Inheriting class and call hidden base constructor

Consider in AssemblyOne 在AssemblyOne中考虑一下

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

public class B : A
{
    internal B (string s) : base(s)
    { }
}

In AssemblyTwo 在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? 显然这是代码味道,但无论是否一个坏主意,是否可以在不更改AssemblyOne的情况下从C的ctor调用B的ctor?

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. 您将无法实例化C类的实例,因为它继承自B,没有公共构造函数。

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. 因此,如果从C类中删除继承问题,由于保护级别的原因,在B的程序集之外创建B类实例仍然存在问题。 You could use reflection to create instances of B, though. 但是,您可以使用反射来创建B的实例。

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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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