在 AssemblyOne 中考虑
public class A
{
internal A (string s)
{ }
}
public class B : A
{
internal B (string s) : base(s)
{ }
}
在 AssemblyTwo 中
public class C : B
{
// Can't do this - ctor in B is inaccessible
public C (string s) : base(s)
}
显然这是一种代码味道,但无论这是否是一个坏主意,是否可以在不更改 AssemblyOne 的情况下从 C 的构造函数调用 B 的构造函数?
最佳答案
暂时忽略程序集二。您将无法实例化类 C 的实例,因为它继承自 B,而 B 没有公共(public)构造函数。
因此,如果您从 C 类中删除继承问题,由于保护级别的原因,在 B 的程序集之外创建 B 类的实例仍然会遇到问题。不过,您可以使用反射来创建 B 的实例。
为了测试的目的,我改变了你的类如下:
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;
}
}
然后我写了一个控制台应用程序来测试:
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();
}
我不建议这样做,这只是不好的做法。我想凡事都有异常(exception),这里的异常(exception)可能是必须处理您无法扩展的第 3 方库。如果不继承,这将为您提供一种实例化和调试的方法。
关于c# - 继承类并调用隐藏的基类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3498440/