c# references a uses b that inherits from c

2020-07-13 07:51发布

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

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?

2条回答
Rolldiameter
2楼-- · 2020-07-13 08:22

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

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

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

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

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 ?

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 :)

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.

查看更多
劫难
3楼-- · 2020-07-13 08:30

Because B is a C, so to create a C, A needs to know about it because it's part of the public surface area of a B.

查看更多
登录 后发表回答