C#中引用一个采用B继承从C [英] c# references a uses b that inherits from c

查看:206
本文介绍了C#中引用一个采用B继承从C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have classes A,B,C like this:

//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,为什么需要有引用到C? 这是没有道理没有?

My question is if B already has reference to C and A has reference to B why do A need to have reference to C? This is not make sense no?

推荐答案

假设类 C 定义如下,它定义了一个名为 PropertyInC财产

Assume class C is defined as below, which defines a property called PropertyInC

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

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

Then when use C's public members through B's instance like this.

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

怎么会编译器会知道什么是 PropertyInC ?你有没有给任何有关它是什么类型的线索?或者如何编译器甚至有机会了解这些财产是否存在?

How come compiler will know what is PropertyInC? Did you gave any clue about what type it is? Or How does the compiler even get a chance to know whether such property exist ?

那么,你可能会说,编译器可以发现,使用的程序集引用的 AsselblyB(组装其中B的生活)的但也不能保证所引用大会将在同一路径或任何有。如果不存在,它将在运行时失败:)

Well, you could argue that compiler can find that using the assembly reference of AsselblyB(assembly where B lives) but then there is no guarantee that referenced assembly will there in the the same path or whatsoever. If not exist it will fail at runtime :)

另外请注意,编译器将允许您编译,如果你没有继承关系,但如果你需要访问 b.CMember 你肯定会添加引用装配其中, C 存在。

Also note that compiler will allow you to compile if you don't have inheritance relationship, but then if you need to access b.CMember you definitely gonna add reference to assembly where C exist.

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

希望这有助于。

Hope this helps.

这篇关于C#中引用一个采用B继承从C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆