共用方式為


out (泛型修飾詞) (C# 參考)

對於泛型型別參數, out 關鍵詞會指定類型參數為covariant。 在通用介面和代理中使用關鍵字 out

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

具有協變型態參數的介面,使其方法能回傳比型別參數所指定的更多導出型態。 例如,因為在 .NET 中, IEnumerable<T>類型 T 是協變的,你可以將該類型的物件 IEnumerable<string> 指派給該 IEnumerable<object> 類型的物件,而不必使用任何特殊的轉換方法。

你可以將協變代理指派給同類型的另一個代理,但其參數更為衍生出泛型。

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

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

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

小提示

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

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

// Covariant interface.
interface ICovariant<out R> { }

// Extending covariant interface.
interface IExtCovariant<out R> : ICovariant<R> { }

// Implementing covariant interface.
class Sample<R> : ICovariant<R> { }

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

        // You can assign istr to iobj because
        // the ICovariant interface is covariant.
        iobj = istr;
    }
}

在一般介面中,若型別參數協變滿足以下條件,則宣告該參數協變:

  • 你只把型別參數當作介面方法的回傳類型,而不是方法參數的類型。

    備註

    這條規則有一個例外。 如果協變介面的方法參數是反變的一般代理,你可以將協變型態作為該代理的通用型別參數。 如需 covariant 和 contravariant 泛型委派的詳細資訊,請參閱 委派中的變異和使用 Func 和 Action 泛型委派的變異數

  • 你不會把型別參數當作介面方法的通用約束。

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

// Covariant delegate.
public delegate R DCovariant<out R>();

// Methods that match the delegate signature.
public static Control SampleControl()
{ return new Control(); }

public static Button SampleButton()
{ return new Button(); }

public void Test()
{
    // Instantiate the delegates with the methods.
    DCovariant<Control> dControl = SampleControl;
    DCovariant<Button> dButton = SampleButton;

    // You can assign dButton to dControl
    // because the DCovariant delegate is covariant.
    dControl = dButton;

    // Invoke the delegate.
    dControl();
}

在通用代理中,如果你只將型別作為方法回傳型別而非方法參數使用,則宣告該型別協變。

C# 語言規格

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

另請參閱