共用方式為


in (通用修飾詞)(C# 參考資料)

對於一般型別參數,請使用 in 關鍵字來允許反變型參數。 在通用介面和代理中使用關鍵字 in

C# 語言參考資料記錄了 C# 語言最新版本。 同時也包含即將推出語言版本公開預覽功能的初步文件。

文件中標示了語言最近三個版本或目前公開預覽版中首次引入的任何功能。

小提示

欲查詢某功能何時首次在 C# 中引入,請參閱 C# 語言版本歷史的條目。

逆變性允許你使用比一般參數所指定的類型更不導出的型別。 此功能允許隱式轉換實作反變介面的類別,以及隱式轉換代理型別。 參考型別支援泛型參數的協變異數與逆變異數,但值型別不支援這些特徵。

你可以在通用介面中宣告一個類型為逆變型,或只有當它定義方法參數的型別而非方法的回傳型別時,才會委派。 In參數refout必須不變,也就是說它們既不是協變也不是反變。

具有反變數型別參數的介面可讓其方法接受衍生型別自變數比介面類型參數所指定的自變數還要少。 例如,在介面中 IComparer<T> ,類型 T 是逆變的。 如果Employee繼承 ,Person你可以將該類型的物件IComparer<Person>指派到該類型的物件IComparer<Employee>上,且不使用任何特殊轉換方法。

你可以將一個反變代理指派給同類型的另一個代理,但其衍生型別參數較少。

如需詳細資訊,請參閱 共變數和反變數

Contravariant 泛型介面

下列範例示範如何宣告、擴充及實作Contravariant泛型介面。 它也會示範如何針對實作這個介面的類別使用隱含轉換。

// Contravariant interface.
interface IContravariant<in A> { }

// Extending contravariant interface.
interface IExtContravariant<in A> : IContravariant<A> { }

// Implementing contravariant interface.
class Sample<A> : IContravariant<A> { }

class Program
{
    static void Test()
    {
        IContravariant<Object> iobj = new Sample<Object>();
        IContravariant<String> istr = new Sample<String>();

        // You can assign iobj to istr because
        // the IContravariant interface is contravariant.
        istr = iobj;
    }
}

Contravariant 泛型委派

下列範例示範如何宣告、具現化及叫用反變數泛型委派。 它也會示範如何隱含地轉換委派類型。

// Contravariant delegate.
public delegate void DContravariant<in A>(A argument);

// Methods that match the delegate signature.
public static void SampleControl(Control control)
{ }
public static void SampleButton(Button button)
{ }

public void Test()
{

    // Instantiating the delegates with the methods.
    DContravariant<Control> dControl = SampleControl;
    DContravariant<Button> dButton = SampleButton;

    // You can assign dControl to dButton
    // because the DContravariant delegate is contravariant.
    dButton = dControl;

    // Invoke the delegate.
    dButton(new Button());
}

C# 語言規格

如需詳細資訊,請參閱<C# 語言規格>。 語言規格是 C# 語法和使用方式的最終來源。

另請參閱