c#引用继承自c的用法b

ila*_*man 5 .net c# reference

我有类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;}
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果B已经引用了C而A引用了B为什么A需要引用C?这没有意义吗?

Sri*_*vel 5

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

public class C
{
   public string PropertyInC {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

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

public void UseBObject()
{
   B BInstance=new B();
   BInstance.PropertyInC = "Whatever";
}
Run Code Online (Sandbox Code Playgroud)

怎么编译器会知道什么是PropertyInC?你有什么类型的线索吗?或者编译器如何有机会知道这些属性是否存在?

好吧,您可以争辩说编译器可以使用AsselblyB(B所在的程序集)的程序集引用找到它,但是不能保证引用的程序集将在同一路径中或任何地方.如果不存在,它将在运行时失败:)

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

public class B
{
   private C CMember{get;set;}//This will compile
   public string Name{get;set;}
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.