gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:14:56 25 4
gpt4 key购买 nike

我有这样的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com