我有一段以下代碼,定義一個接口iInterface,cBase實現iInterface,cChild繼承cBase,UML爲css
預期是想要cBase.F()的執行邏輯,同時須要cChild的返回值,因此FF預期的輸出html
1: namespace ConsoleApplication1
2: {
3: class Program
4: {
5: static void Main(string[] args)
6: {
7: iInterface inf = new cChild();
8: FF(inf);
9:
10: Console.ReadLine();
11: }
12: static public void FF(iInterface inf)
13: {
14: Console.WriteLine(inf.F());
15: }
16: }
17:
18: public interface iInterface
19: {
20: string F();
21: }
22: public class cBase : iInterface
23: {
24: public string F()
25: {
26: Console.WriteLine("base.F1");
27: return "this is base";
28: }
29: }
30: public class cChild : cBase
31: {
32: public string F()
33: {
34: base.F();
35: return "this is child";
36: }
37: }
38: }
可是實際的結果是隻能call到cBase的F函數,輸出」this is base」函數
緣由是咱們定義的inf類型爲iInterface,同時賦值的對象類型爲cChild,可是cChild是沒有實現iInterface的(繼承至實現了接口的class也是不行的)。this
實際運行時,inf向上找到了cBase有實現iInterface,因此調用了它的實現。spa
想達到預期的結果,能夠將cChild也實現iInterface,以下:code
1: public class cChild : cBase, iInterface
2: {
3: public string F()
4: {
5: base.F();
6: return "this is child";
7: }
8: }
修改後的UML爲htm
輸出結果爲:對象