c# - 继承类并调用隐藏的基类构造函数

标签 c#

在 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/

相关文章:

c# - 在 LoginView 中显示用户名

c# - 如何将 Image<Gray, Byte> 转换为 Image<Gray, float>?

c# - 指示远程主机已关闭连接的 NetworkStream.Read 的替代方法?

c# - 运行时尝试查找 exe/dll 而不是 .winmd 引用

c# - DataGridView 单元格在 CellLeave 上为空

c# - 为什么不能从 C# 中的值类型派生?

c# - TCP speed tester 算法题

c# - 在 C# 中编写 List<> 的前 3 个字母

c# - 将 Rtf 格式转换为 HTML

c# - 将锁迁移到 TPL