共用方式為


共變數和反變數 (C#)

在 C# 中,協變性和逆變性允許陣列類型、委派類型和泛型型別引數的隱含參考類型轉換。 共變性保留指派相容性,而反變性則反轉它。

下列程式代碼示範指派相容性、共變數和反變數之間的差異。

// Assignment compatibility.
string str = "test";  
// An object of a more derived type is assigned to an object of a less derived type.
object obj = str;  
  
// Covariance.
IEnumerable<string> strings = new List<string>();  
// An object that is instantiated with a more derived type argument
// is assigned to an object instantiated with a less derived type argument.
// Assignment compatibility is preserved.
IEnumerable<object> objects = strings;  
  
// Contravariance.
// Assume that the following method is in the class:
static void SetObject(object o) { }
Action<object> actObject = SetObject;  
// An object that is instantiated with a less derived type argument
// is assigned to an object instantiated with a more derived type argument.
// Assignment compatibility is reversed.
Action<string> actString = actObject;  

陣列的共變性允許您將更多衍生類型的陣列隱含地轉換成較少衍生類型的陣列。 但這項作業的類型並不安全,如下列程式代碼範例所示。

object[] array = new String[10];  
// The following statement produces a run-time exception.  
// array[0] = 10;  

方法群組的共變數和反變數支持允許比對具有委派類型的方法簽章。 這可讓您指派給委派委託,不僅是具有相符簽章的方法,還可以指派傳回更多衍生類型的方法(共變性)或接受具有比委派類型所指定之衍生類型少的參數的方法(反變性)。 如需詳細資訊,請參閱 委派中的變異 (C#)使用委派中的變異 (C#)

下列程式代碼範例顯示方法群組的共變數和反變數支援。

static object GetObject() { return null; }  
static void SetObject(object obj) { }  
  
static string GetString() { return ""; }  
static void SetString(string str) { }  
  
static void Test()  
{  
    // Covariance. A delegate specifies a return type as object,  
    // but you can assign a method that returns a string.  
    Func<object> del = GetString;  
  
    // Contravariance. A delegate specifies a parameter type as string,  
    // but you can assign a method that takes an object.  
    Action<string> del2 = SetObject;  
}  

在 .NET Framework 4 和更新版本中,C# 支援泛型介面和委派中的共變數和反變數,並允許隱含轉換泛型類型參數。 如需詳細資訊,請參閱 泛型介面中的變數 (C#)委派中的變數 (C#)

下列程式代碼範例顯示泛型介面的隱含參考轉換。

IEnumerable<String> strings = new List<String>();  
IEnumerable<Object> objects = strings;  

如果泛型參數宣告為 covariant 或 contravariant,則稱為 型介面或委派。 C# 可讓您建立自己的變體介面和委派。 如需詳細資訊,請參閱建立 Variant 泛型介面(C#)委派中的變異數(C#)。

標題 說明
泛型介面中的變數 (C#) 討論泛型介面中的共變數和反變數,並提供 .NET 中的變體泛型介面清單。
建立可變泛型介面(C#) 示範如何建立自定義變體介面。
在泛型集合的介面中使用變異數 (C#) 示範如何在IEnumerable<T>IComparable<T> 介面中支援的共變數和反變數有助於您重複利用程式碼。
委派中的差異 (C#) 討論泛型和非泛型委派中的共變和逆變,並提供 .NET 中的變體泛型委派清單。
在委派中使用變數 (C#) 示範如何在非泛型委派中使用共變數和反變數支援,以比對方法簽章與委派類型。
使用運算和動作泛型委派的變異數 (C#) 顯示 FuncAction 委任物件中對共變數和反變數的支援如何協助您重複使用代碼。