C# 引用 A 使用从 C 继承的 B

本文关键字:继承 引用 | 更新日期: 2023-09-27 17:56:51

我有这样的类A,B,C:

//Class A is in Console application that has reference to class library that has class B
public class A
{
    public void UseBObject()
    {
       B BInstance=new B();   // error C is defined in assembly that is not referenced you must add  reference that contains C... 
    }
} 

//Class library that reference another library the contains C class
public class B : C
{
   public string Name{get;set;}
}
我的问题是,如果 B 已经引用了 C,而 A 引用

了 B,为什么 A 需要引用 C?这没有意义不是吗?

C# 引用 A 使用从 C 继承的 B

假设类C定义如下,它定义了一个名为PropertyInC的属性

public class C
{
   public string PropertyInC {get;set;}
}

然后当通过 B 的实例像这样使用 C 的公共成员时。

public void UseBObject()
{
   B BInstance=new B();
   BInstance.PropertyInC = "Whatever";
}

编译器怎么会知道什么是PropertyInC?你有没有给出任何关于它是什么类型的线索?或者编译器如何有机会知道这样的属性是否存在?

好吧,你可能会争辩说编译器可以使用 AsselblyB(B 所在的程序集)的程序集引用来发现,但不能保证引用的程序集会在同一路径或任何路径中。如果不存在,它将在运行时失败:)

另请注意,如果您没有继承关系,编译器将允许您进行编译,但是如果您需要访问b.CMember您肯定会在存在C的地方添加对程序集的引用。

public class B
{
   private C CMember{get;set;}//This will compile
   public string Name{get;set;}
}

希望这有帮助。

因为 B 是 C,

所以要创建 C,A 需要知道它,因为它是 B 的公共表面积的一部分。