協變和逆變

2021-09-24 02:30:08 字數 1463 閱讀 8236

二、真正的協變和逆變

概念:1、以前的泛型系統(或者說沒有in/out關鍵字時),是不能「變」的,無論是「逆」還是「順(協)」。

2、當前僅支援介面和委託的逆變與協變 ,不支援類和方法。但陣列也有協變性。

3、值型別不參與逆變與協變。

協變:foo= foo

public class testoutwhere t : new()

//*****[協變]泛型介面demo*****

//1、建立泛型介面

public inte***ce imyinte***cea //預設不支援協變與逆變

public inte***ce imyinte***ceb //設定支援協變

//public inte***ce imyinte***cec//

//2、建立介面變數

public imyinte***ceainteraobject = null;

public imyinte***ceainterastring = null;

public imyinte***cebinterbobject = null;

public imyinte***cebinterbstring = null;

public imyinte***cebinterbint = null;

//3、驗證結果

public void testinte***ce()

}

逆變:foo= foo

public class testinwhere t : new()

//*****[逆變]泛型介面*****

//1、建立泛型介面

public inte***ce imyinte***cea //預設不支援協變與逆變

public inte***ce imyinte***ceb //設定支援逆變

//public inte***ce imyinte***cec//

//2、建立介面變數

public imyinte***ceainteraobject = null;

public imyinte***ceainterastring = null;

public imyinte***cebinterbobject = null;

public imyinte***cebinterbstring = null;

public imyinte***cebinterbint = null;

//3、驗證結果

public void testinte***ce()

}

協變和逆變

協變和逆變都是術語,前者指能夠使用比原始指定的派生型別的派生程度更大的型別,後者指能夠使用比原始指定的派生型別的派生程度更小的型別。using system using system.collections.generic using system.text class derived base s...

協變和逆變

假設有這樣乙個類 class person icloneable 但是由於我們知道是返回乙個person類的例項,所以返回型別 object 寫在這裡總會覺得很彆扭,我們希望寫成 class person icloneable 顯然,這是錯的 雖然這是錯的,但這就是返回型別的協變性,只是非泛型介面和...

C 協變逆變

1.泛型的協變逆變 注意 只能放在介面或者委託的泛型引數前面 1 委託泛型引數 static class testconsole private static argumentexception test1 object obj private static exception test2 stri...