c# 引用 a 使用继承自 c 的 b

标签 c# .net 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;}
}

我的问题是,如果 B 已经引用了 C,并且 A 引用了 B,为什么 A 需要引用 C? 这没有道理吧?

最佳答案

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

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

然后像这样通过B的实例使用C的公共(public)成员。

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;}
}

希望这对您有所帮助。

关于c# 引用 a 使用继承自 c 的 b,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22893988/

相关文章:

c# - 如何关闭 Entity Framework Core 5 中的所有约定

.net - .NET有没有 "advanced"测试框架?

.net - ASP.NET MVC 2 中是否可以嵌套区域?

c# - 是否可以通过反射设置静态类的这个静态私有(private)成员?

c# - 如何在 C# 中导入原始 RSS 提要?

reference - 如何制作引用文献的副本? (生活问题)

node.js - 名为 '[DEFAULT]' 的 Firebase 应用程序已经存在,并且 google firebase 引用在服务器上不起作用

c++ - 需要帮助解码这个 typedef

c# - 如何将这两行重构为一条语句?

c# - Entity Framework - 插入具有多个模型和数据库的实体