Delegate.CreateDelegate Yöntem

Tanım

Belirtilen türde bir temsilci oluşturur.

Aşırı Yüklemeler

Name Description
CreateDelegate(Type, Object, String, Boolean, Boolean)

Belirtilen sınıf örneğinde çağrılacak belirtilen örnek yöntemini temsil eden belirtilen türde bir temsilci oluşturur; belirtilen büyük/küçük harf duyarlılığı ve bağlanma hatasında belirtilen davranış.

CreateDelegate(Type, Type, String, Boolean)

Belirtilen büyük/küçük harf duyarlılığı ile belirtilen sınıfın belirtilen statik yöntemini temsil eden belirtilen türde bir temsilci oluşturur.

CreateDelegate(Type, Object, String, Boolean)

Belirtilen büyük/küçük harf duyarlılığıyla belirtilen sınıf örneğinde çağrılacak belirtilen örnek yöntemini temsil eden belirtilen türde bir temsilci oluşturur.

CreateDelegate(Type, Object, MethodInfo, Boolean)

Belirtilen statik veya örnek yöntemini temsil eden, belirtilen ilk bağımsız değişken ve bağlama hatasında belirtilen davranışla belirtilen türde bir temsilci oluşturur.

CreateDelegate(Type, Type, String, Boolean, Boolean)

Belirtilen sınıfın belirtilen statik yöntemini temsil eden belirtilen türde, belirtilen büyük/küçük harf duyarlılığı ve bağlama hatasında belirtilen davranış ile bir temsilci oluşturur.

CreateDelegate(Type, MethodInfo, Boolean)

Belirtilen statik yöntemi temsil etmek için belirtilen türün bir temsilcisini oluşturur ve bağlanma hatasında belirtilen davranış gösterilir.

CreateDelegate(Type, Object, String)

Belirtilen sınıf örneğinde çağrılacak belirtilen örnek yöntemini temsil eden belirtilen türde bir temsilci oluşturur.

CreateDelegate(Type, Object, MethodInfo)

Belirtilen ilk bağımsız değişkenle belirtilen statik veya örnek yöntemini temsil eden belirtilen türde bir temsilci oluşturur.

CreateDelegate(Type, MethodInfo)

Belirtilen yöntemi temsil etmek için belirtilen türde bir temsilci oluşturur.

CreateDelegate(Type, Type, String)

Belirtilen sınıfın belirtilen statik yöntemini temsil eden belirtilen türde bir temsilci oluşturur.

CreateDelegate(Type, Object, String, Boolean, Boolean)

Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs

Belirtilen sınıf örneğinde çağrılacak belirtilen örnek yöntemini temsil eden belirtilen türde bir temsilci oluşturur; belirtilen büyük/küçük harf duyarlılığı ve bağlanma hatasında belirtilen davranış.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ target, System::String ^ method, bool ignoreCase, bool throwOnBindFailure);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The target method might be removed")]
public static Delegate? CreateDelegate(Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure);
public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure);
public static Delegate? CreateDelegate(Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The target method might be removed")>]
static member CreateDelegate : Type * obj * string * bool * bool -> Delegate
static member CreateDelegate : Type * obj * string * bool * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Object, method As String, ignoreCase As Boolean, throwOnBindFailure As Boolean) As Delegate

Parametreler

type
Type

Type Oluşturulacak temsilci.

target
Object

Üzerinde çağrılan method sınıf örneği.

method
String

Temsilcinin temsil etmek üzere olduğu örnek yönteminin adı.

ignoreCase
Boolean

Yöntemin adı karşılaştırılırken büyük/küçük harf yoksayılıp yoksayılmayacağını gösteren Boole değeri.

throwOnBindFailure
Boolean

true bağlanamıyorsa method bir özel durum oluşturur; aksi takdirde , false.

Döndürülenler

Belirtilen sınıf örneğinde çağrılacak belirtilen örnek yöntemini temsil eden belirtilen türde bir temsilci.

Öznitelikler

Özel durumlar

type, null'e eşittir.

-veya-

target, null'e eşittir.

-veya-

method, null'e eşittir.

type devralmıyor MulticastDelegate.

-veya-

type bir RuntimeTypedeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

-veya-

method bir örnek yöntemi değildir.

-veya-

method bağlanamıyor, örneğin bulunamadığı ve throwOnBindFailure olduğu trueiçin.

Invoke yöntemi type bulunamadı.

Çağıranın erişimi methodiçin gerekli izinlere sahip değil.

Açıklamalar

Bu yöntem yalnızca örnek yöntemleri için temsilciler oluşturur. Örnek yöntemi, sınıfın bir örneğiyle ilişkilendirilmiş bir yöntemdir; statik yöntem, sınıfın kendisiyle ilişkili bir yöntemdir.

Ayrıca bkz.

Şunlara uygulanır

CreateDelegate(Type, Type, String, Boolean)

Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs

Belirtilen büyük/küçük harf duyarlılığı ile belirtilen sınıfın belirtilen statik yöntemini temsil eden belirtilen türde bir temsilci oluşturur.

public:
 static Delegate ^ CreateDelegate(Type ^ type, Type ^ target, System::String ^ method, bool ignoreCase);
public static Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The target method might be removed")]
public static Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase);
static member CreateDelegate : Type * Type * string * bool -> Delegate
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The target method might be removed")>]
static member CreateDelegate : Type * Type * string * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Type, method As String, ignoreCase As Boolean) As Delegate

Parametreler

type
Type

Type Oluşturulacak temsilci.

target
Type

Type uygulayan sınıfını temsil edenmethod.

method
String

Temsilcinin temsil etmek üzere olduğu statik yöntemin adı.

ignoreCase
Boolean

Yöntemin adı karşılaştırılırken büyük/küçük harf yoksayılıp yoksayılmayacağını gösteren Boole değeri.

Döndürülenler

Belirtilen sınıfın belirtilen statik yöntemini temsil eden belirtilen türün temsilcisi.

Öznitelikler

Özel durumlar

type, null'e eşittir.

-veya-

target, null'e eşittir.

-veya-

method, null'e eşittir.

type devralmıyor MulticastDelegate.

-veya-

type bir RuntimeTypedeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

-veya-

target bir RuntimeTypedeğildir.

-veya-

target açık bir genel türdür. Yani, özelliği ContainsGenericParameters şeklindedir true.

-veya-

method bir static yöntemi değildir (Visual Basic'de Shared yöntemi).

-veya-

method bağlanamıyor, örneğin bulunamadığından.

Invoke yöntemi type bulunamadı.

Çağıranın erişimi methodiçin gerekli izinlere sahip değil.

Açıklamalar

Bu yöntem yalnızca statik yöntemler için temsilciler oluşturur. Örnek yöntemi, sınıfın bir örneğiyle ilişkilendirilmiş bir yöntemdir; statik yöntem, sınıfın kendisiyle ilişkili bir yöntemdir.

Bu yöntem aşırı yüklemesi, için CreateDelegate(Type, Type, String, Boolean, Boolean)belirterek yöntem aşırı yüklemesini true çağırmaya throwOnBindFailure eşdeğerdir.

Ayrıca bkz.

Şunlara uygulanır

CreateDelegate(Type, Object, String, Boolean)

Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs

Belirtilen büyük/küçük harf duyarlılığıyla belirtilen sınıf örneğinde çağrılacak belirtilen örnek yöntemini temsil eden belirtilen türde bir temsilci oluşturur.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ target, System::String ^ method, bool ignoreCase);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The target method might be removed")]
public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase);
public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The target method might be removed")>]
static member CreateDelegate : Type * obj * string * bool -> Delegate
static member CreateDelegate : Type * obj * string * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Object, method As String, ignoreCase As Boolean) As Delegate

Parametreler

type
Type

Type Oluşturulacak temsilci.

target
Object

Üzerinde çağrılan method sınıf örneği.

method
String

Temsilcinin temsil etmek üzere olduğu örnek yönteminin adı.

ignoreCase
Boolean

Yöntemin adı karşılaştırılırken büyük/küçük harf yoksayılıp yoksayılmayacağını gösteren Boole değeri.

Döndürülenler

Belirtilen sınıf örneğinde çağrılacak belirtilen örnek yöntemini temsil eden belirtilen türde bir temsilci.

Öznitelikler

Özel durumlar

type, null'e eşittir.

-veya-

target, null'e eşittir.

-veya-

method, null'e eşittir.

type devralmıyor MulticastDelegate.

-veya-

type bir RuntimeTypedeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

-veya-

method bir örnek yöntemi değildir.

-veya-

method bağlanamıyor, örneğin bulunamadığından.

Invoke yöntemi type bulunamadı.

Çağıranın erişimi methodiçin gerekli izinlere sahip değil.

Açıklamalar

Bu yöntem yalnızca örnek yöntemleri için temsilciler oluşturur. Örnek yöntemi, sınıfın bir örneğiyle ilişkilendirilmiş bir yöntemdir; statik yöntem, sınıfın kendisiyle ilişkili bir yöntemdir.

Bu yöntem aşırı yüklemesi, için CreateDelegate(Type, Object, String, Boolean, Boolean)belirterek yöntem aşırı yüklemesini true çağırmaya throwOnBindFailure eşdeğerdir.

Ayrıca bkz.

Şunlara uygulanır

CreateDelegate(Type, Object, MethodInfo, Boolean)

Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs

Belirtilen statik veya örnek yöntemini temsil eden, belirtilen ilk bağımsız değişken ve bağlama hatasında belirtilen davranışla belirtilen türde bir temsilci oluşturur.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ firstArgument, System::Reflection::MethodInfo ^ method, bool throwOnBindFailure);
public static Delegate? CreateDelegate(Type type, object? firstArgument, System.Reflection.MethodInfo method, bool throwOnBindFailure);
public static Delegate CreateDelegate(Type type, object firstArgument, System.Reflection.MethodInfo method, bool throwOnBindFailure);
static member CreateDelegate : Type * obj * System.Reflection.MethodInfo * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, firstArgument As Object, method As MethodInfo, throwOnBindFailure As Boolean) As Delegate

Parametreler

type
Type

Type Oluşturulacak temsilci türünü temsil eden bir.

firstArgument
Object

Temsilcinin Object temsil ettiği yöntemin ilk bağımsız değişkeni olan. Örneğin yöntemleri, örnek türüyle uyumlu olmalıdır.

method
MethodInfo

Temsilcinin MethodInfo temsil etmek üzere olduğu statik veya örnek yöntemini açıklayan.

throwOnBindFailure
Boolean

true bağlanamıyorsa method bir özel durum oluşturur; aksi takdirde , false.

Döndürülenler

Belirtilen statik veya örnek yöntemini temsil eden belirtilen türde bir temsilci veya null ise throwOnBindFailurefalse ve temsilcisi ile methodbağlantı kurulamıyor.

Özel durumlar

type, null'e eşittir.

-veya-

method, null'e eşittir.

type devralmıyor MulticastDelegate.

-veya-

type bir RuntimeTypedeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

-veya-

method bağlanamaz ve throwOnBindFailure şeklindedir true.

-veya-

method bir RuntimeMethodInfodeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

Invoke yöntemi type bulunamadı.

Çağıranın erişimi methodiçin gerekli izinlere sahip değil.

Açıklamalar

Bu yöntem aşırı yüklemesi ve CreateDelegate(Type, Object, MethodInfo) her zaman bağlama hatasına neden olan yöntem aşırı yüklemesi, temsilci oluşturmanın en esnek yolunu sağlar. Bunları, ilk bağımsız değişkenle veya bağımsız değişken olmadan statik veya örnek yöntemleri için temsilciler oluşturmak için kullanabilirsiniz.

Note

İlk bağımsız değişken sağlamazsanız, daha iyi performans için yöntem aşırı yüklemesini CreateDelegate(Type, MethodInfo, Boolean) kullanın.

Temsilci türü ve yöntemi uyumlu dönüş türlerine sahip olmalıdır. Yani, method dönüş türü typedönüş türüne atanabilir olmalıdır.

firstArgument, bu aşırı yüklemelerin ikinci parametresi, temsilcinin temsil ettiği yöntemin ilk bağımsız değişkenidir. firstArgument sağlanırsa, temsilci her çağrıldığında firstArgumentfirstArgument'e iletilir; 'nin temsilciye bağlı olduğu ve temsilcinin ilk bağımsız değişkeni üzerinde işlevsel olarak kapandığı söylenir. method static ise (Visual Basic'teShared), temsilci çağrılırken sağlanan bağımsız değişken listesi ilk parametre dışındaki tüm parametreleri içerir; method bir örnek yöntemiyse, gizli örnek parametresine (C# dilinde firstArgument veya Visual Basic'teki this tarafından temsil edilen) Me geçirilir.

firstArgument sağlanırsa, method ilk parametresi bir başvuru türü olmalı ve firstArgument bu türle uyumlu olmalıdır.

Important

method static (Visual Basic'teShared) ve ilk parametresi Object veya ValueTypetüründeyse, firstArgument bir değer türü olabilir. Bu durumda firstArgument otomatik olarak kutulanır. C# veya Visual Basic işlev çağrısında olduğu gibi diğer bağımsız değişkenler için otomatik kutulama gerçekleşmez.

firstArgument null referans ve method bir örnek metot ise, sonuç delege tipi type ve methodimzalarına bağlıdır.

  • type imzası açıkça methodgizli ilk parametresini içeriyorsa, temsilcinin açık bir örnek yöntemini temsil ettiğini söylenir. Temsilci çağrıldığında, bağımsız değişken listesindeki ilk bağımsız değişken methodgizli örnek parametresine geçirilir.
  • method ve type imzaları eşleşiyorsa (yani, tüm parametre türleri uyumludur), temsilcinin null referansı üzerinde kapatıldığı söylenir. Temsilciyi çağırmak, null örnekte bir örnek yöntemini çağırmak gibidir ve bu özellikle yararlı bir işlem değildir.

firstArgument null başvuruysa ve method statikse, sonuç temsilci türü type ve methodimzalarına bağlıdır:

  • method ve type imzası eşleşiyorsa (diğer bir ifadeyle tüm parametre türleri uyumludur), temsilcinin açık statik bir yöntemi temsil olduğu söylenir. Bu, statik yöntemler için en yaygın durumdur. Bu durumda, CreateDelegate(Type, MethodInfo) metot aşırı yüklemesini kullanarak biraz daha iyi bir performans elde edebilirsiniz.
  • type imzası, method'in ikinci parametresiyle başlıyorsa ve geri kalan parametre türleri uyumluysa, temsilcinin null bir referans üzerinde kapatıldığı söylenir. Temsilci çağrıldığında, method'ın ilk parametresine boş bir referans geçirilir.

Example

Aşağıdaki kod örneği, tek bir temsilci türünün gösterebileceği tüm yöntemleri gösterir: örnek yöntemi üzerinden kapatılır, örnek yöntemi üzerinden açılır, statik yöntem üzerinden açılır ve statik yöntem üzerinden kapatılır.

Kod örneği, C ve Folmak üzere iki sınıfı ve Dtüründe bir bağımsız değişkeni olan bir temsilci türü C tanımlar. Sınıfların, M1, M3ve M4ile eşleşen statik ve örnek yöntemleri vardır ve sınıf C'ün, bağımsız değişkeni olmayan bir örnek yöntemi M2 sahiptir.

Example adlı üçüncü sınıf, temsilcileri oluşturan kodu içerir.

  • Temsilciler, M1 örnek yöntemi ile C ve Ftürleri için oluşturulur; her biri ilgili türün bir örneğine göre kapatılır. M1 yönteminin C türü, bağlı örneğin ve bağımsız değişkenin ID özelliklerini görüntüler.
  • M2türünde yöntem C için bir temsilci oluşturulur. Bu, temsilci bağımsız değişkeninin örnek yöntemindeki gizli ilk bağımsız değişkeni temsil ettiği açık örnek temsilcisidir. Yöntemin başka parametresi yok. Statik bir yöntemmiş gibi çağrılır.
  • Temsilciler, M3 statik yöntemi için C türü ve Ftürü olarak oluşturulur; bunlar açık statik temsilcilerdir.
  • Son olarak, M4 türüne ve Ctürüne ait olan statik yöntem F için temsilciler oluşturulur; her yöntemin bildirim türü ilk bağımsız değişken olarak görev yapar ve türün bir örneği sağlandığı için, temsilciler ilk bağımsız değişkenleri üzerine kapatılır. M4 yönteminin C türü, bağlı örneğin ve bağımsız değişkenin ID özelliklerini görüntüler.
using System;
using System.Reflection;

// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
//
public delegate void D(C1 c);

// Declare two sample classes, C1 and F. Class C1 has an ID
// property so instances can be identified.
//
public class C1
{
    private int id;
    public int ID => id;
    public C1(int id) => this.id = id;

    public void M1(C1 c)
    {
        Console.WriteLine("Instance method M1(C1 c) on C1:  this.id = {0}, c.ID = {1}",
            this.id, c.ID);
    }

    public void M2()
    {
        Console.WriteLine($"Instance method M2() on C1:  this.id = {this.id}");
    }

    public static void M3(C1 c)
    {
        Console.WriteLine($"Static method M3(C1 c) on C1:  c.ID = {c.ID}");
    }

    public static void M4(C1 c1, C1 c2)
    {
        Console.WriteLine("Static method M4(C1 c1, C1 c2) on C1:  c1.ID = {0}, c2.ID = {1}",
            c1.ID, c2.ID);
    }
}

public class F
{
    public void M1(C1 c)
    {
        Console.WriteLine($"Instance method M1(C1 c) on F:  c.ID = {c.ID}");
    }

    public static void M3(C1 c)
    {
        Console.WriteLine($"Static method M3(C1 c) on F:  c.ID = {c.ID}");
    }

    public static void M4(F f, C1 c)
    {
        Console.WriteLine($"Static method M4(F f, C1 c) on F:  c.ID = {c.ID}");
    }
}

public class Example
{
    public static void Main()
    {
        C1 c1 = new (42);
        C1 c2 = new (1491);
        F f1 = new ();

        D d;

        // Instance method with one argument of type C1.
        MethodInfo cmi1 = typeof(C1).GetMethod("M1");
        // Instance method with no arguments.
        MethodInfo cmi2 = typeof(C1).GetMethod("M2");
        // Static method with one argument of type C1.
        MethodInfo cmi3 = typeof(C1).GetMethod("M3");
        // Static method with two arguments of type C1.
        MethodInfo cmi4 = typeof(C1).GetMethod("M4");

        // Instance method with one argument of type C1.
        MethodInfo fmi1 = typeof(F).GetMethod("M1");
        // Static method with one argument of type C1.
        MethodInfo fmi3 = typeof(F).GetMethod("M3");
        // Static method with an argument of type F and an argument
        // of type C1.
        MethodInfo fmi4 = typeof(F).GetMethod("M4");

        Console.WriteLine("\nAn instance method on any type, with an argument of type C1.");
        // D can represent any instance method that exactly matches its
        // signature. Methods on C1 and F are shown here.
        //
        d = (D)Delegate.CreateDelegate(typeof(D), c1, cmi1);
        d(c2);
        d = (D)Delegate.CreateDelegate(typeof(D), f1, fmi1);
        d(c2);

        Console.WriteLine("\nAn instance method on C1 with no arguments.");
        // D can represent an instance method on C1 that has no arguments;
        // in this case, the argument of D represents the hidden first
        // argument of any instance method. The delegate acts like a
        // static method, and an instance of C1 must be passed each time
        // it is invoked.
        //
        d = (D)Delegate.CreateDelegate(typeof(D), null, cmi2);
        d(c1);

        Console.WriteLine("\nA static method on any type, with an argument of type C1.");
        // D can represent any static method with the same signature.
        // Methods on F and C1 are shown here.
        //
        d = (D)Delegate.CreateDelegate(typeof(D), null, cmi3);
        d(c1);
        d = (D)Delegate.CreateDelegate(typeof(D), null, fmi3);
        d(c1);

        Console.WriteLine("\nA static method on any type, with an argument of");
        Console.WriteLine("    that type and an argument of type C1.");
        // D can represent any static method with one argument of the
        // type the method belongs and a second argument of type C1.
        // In this case, the method is closed over the instance of
        // supplied for the its first argument, and acts like an instance
        // method. Methods on F and C1 are shown here.
        //
        d = (D)Delegate.CreateDelegate(typeof(D), c1, cmi4);
        d(c2);
        Delegate test =
            Delegate.CreateDelegate(typeof(D), f1, fmi4, false);

        // This final example specifies false for throwOnBindFailure
        // in the call to CreateDelegate, so the variable 'test'
        // contains Nothing if the method fails to bind (for
        // example, if fmi4 happened to represent a method of
        // some class other than F).
        //
        if (test != null)
        {
            d = (D)test;
            d(c2);
        }
    }
}

/* This code example produces the following output:

An instance method on any type, with an argument of type C1.
Instance method M1(C1 c) on C1:  this.id = 42, c.ID = 1491
Instance method M1(C1 c) on F:  c.ID = 1491

An instance method on C1 with no arguments.
Instance method M2() on C1:  this.id = 42

A static method on any type, with an argument of type C1.
Static method M3(C1 c) on C1:  c.ID = 42
Static method M3(C1 c) on F:  c.ID = 42

A static method on any type, with an argument of
    that type and an argument of type C1.
Static method M4(C1 c1, C1 c2) on C1:  c1.ID = 42, c2.ID = 1491
Static method M4(F f, C1 c) on F:  c.ID = 1491
*/
open System

// Declare two sample classes, C and F. Class C has an ID
// property so instances can be identified.
type C(id) =
    member _.ID = id 

    member _.M1(c: C) =
        printfn $"Instance method M1(C c) on C:  this.id = {id}, c.ID = {c.ID}"

    member _.M2() =
        printfn $"Instance method M2() on C:  this.id = {id}"

    static member M3(c: C) =
        printfn $"Static method M3(C c) on C:  c.ID = {c.ID}"

    static member M4(c1: C, c2: C) =
        printfn $"Static method M4(C c1, C c2) on C:  c1.ID = {c1.ID}, c2.ID = {c2.ID}"

// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
type D = delegate of C -> unit


type F() =
    member _.M1(c: C) =
        printfn $"Instance method M1(C c) on F:  c.ID = {c.ID}"

    member _.M3(c: C) =
        printfn $"Static method M3(C c) on F:  c.ID = {c.ID}"

    member _.M4(f: F, c: C) =
        printfn $"Static method M4(F f, C c) on F:  c.ID = {c.ID}"

[<EntryPoint>]
let main _ =
    let c1 = C 42
    let c2 = C 1491
    let f1 = F()

    // Instance method with one argument of type C.
    let cmi1 = typeof<C>.GetMethod "M1"
    // Instance method with no arguments.
    let cmi2 = typeof<C>.GetMethod "M2"
    // Static method with one argument of type C.
    let cmi3 = typeof<C>.GetMethod "M3"
    // Static method with two arguments of type C.
    let cmi4 = typeof<C>.GetMethod "M4"

    // Instance method with one argument of type C.
    let fmi1 = typeof<F>.GetMethod "M1"
    // Static method with one argument of type C.
    let fmi3 = typeof<F>.GetMethod "M3"
    // Static method with an argument of type F and an argument
    // of type C.
    let fmi4 = typeof<F>.GetMethod "M4"

    printfn "\nAn instance method on any type, with an argument of type C."
    // D can represent any instance method that exactly matches its
    // signature. Methods on C and F are shown here.
    let d = Delegate.CreateDelegate(typeof<D>, c1, cmi1) :?> D
    d.Invoke c2
    let d =  Delegate.CreateDelegate(typeof<D>, f1, fmi1) :?> D
    d.Invoke c2

    Console.WriteLine("\nAn instance method on C with no arguments.")
    // D can represent an instance method on C that has no arguments
    // in this case, the argument of D represents the hidden first
    // argument of any instance method. The delegate acts like a
    // static method, and an instance of C must be passed each time
    // it is invoked.
    let d = Delegate.CreateDelegate(typeof<D>, null, cmi2) :?> D
    d.Invoke c1

    printfn "\nA static method on any type, with an argument of type C."
    // D can represent any static method with the same signature.
    // Methods on F and C are shown here.
    let d = Delegate.CreateDelegate(typeof<D>, null, cmi3) :?> D
    d.Invoke c1
    let d = Delegate.CreateDelegate(typeof<D>, null, fmi3) :?> D
    d.Invoke c1

    printfn "\nA static method on any type, with an argument of"
    printfn "    that type and an argument of type C."
    // D can represent any static method with one argument of the
    // type the method belongs and a second argument of type C.
    // In this case, the method is closed over the instance of
    // supplied for the its first argument, and acts like an instance
    // method. Methods on F and C are shown here.
    let d = Delegate.CreateDelegate(typeof<D>, c1, cmi4) :?> D
    d.Invoke c2
    let test =
        Delegate.CreateDelegate(typeof<D>, f1, fmi4, false)

    // This final example specifies false for throwOnBindFailure
    // in the call to CreateDelegate, so the variable 'test'
    // contains Nothing if the method fails to bind (for
    // example, if fmi4 happened to represent a method of
    // some class other than F).
    match test with
    | :? D as d ->
        d.Invoke c2
    | _ -> ()
    0

// This code example produces the following output:
//     An instance method on any type, with an argument of type C.
//     Instance method M1(C c) on C:  this.id = 42, c.ID = 1491
//     Instance method M1(C c) on F:  c.ID = 1491
//    
//     An instance method on C with no arguments.
//     Instance method M2() on C:  this.id = 42
//    
//     A static method on any type, with an argument of type C.
//     Static method M3(C c) on C:  c.ID = 42
//     Static method M3(C c) on F:  c.ID = 42
//    
//     A static method on any type, with an argument of
//         that type and an argument of type C.
//     Static method M4(C c1, C c2) on C:  c1.ID = 42, c2.ID = 1491
//     Static method M4(F f, C c) on F:  c.ID = 1491
Imports System.Reflection
Imports System.Security.Permissions

' Declare a delegate type. The object of this code example
' is to show all the methods this delegate can bind to.
'
Public Delegate Sub D(ByVal c As C) 

' Declare two sample classes, C and F. Class C has an ID
' property so instances can be identified.
'
Public Class C

    Private _id As Integer

    Public ReadOnly Property ID() As Integer 
        Get
            Return _id
        End Get
    End Property

    Public Sub New(ByVal newId As Integer) 
        Me._id = newId
    End Sub
    
    Public Sub M1(ByVal c As C) 
        Console.WriteLine("Instance method M1(c As C) on C:  this.id = {0}, c.ID = {1}", _
            Me.id, c.ID)
    End Sub
    
    Public Sub M2() 
        Console.WriteLine("Instance method M2() on C:  this.id = {0}", Me.id)
    End Sub
    
    Public Shared Sub M3(ByVal c As C) 
        Console.WriteLine("Shared method M3(c As C) on C:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M4(ByVal c1 As C, ByVal c2 As C) 
        Console.WriteLine("Shared method M4(c1 As C, c2 As C) on C:  c1.ID = {0}, c2.ID = {1}", _
            c1.ID, c2.ID)
    End Sub
End Class


Public Class F
    
    Public Sub M1(ByVal c As C) 
        Console.WriteLine("Instance method M1(c As C) on F:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M3(ByVal c As C) 
        Console.WriteLine("Shared method M3(c As C) on F:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M4(ByVal f As F, ByVal c As C) 
        Console.WriteLine("Shared method M4(f As F, c As C) on F:  c.ID = {0}", c.ID)
    End Sub
End Class

Public Class Example5

    Public Shared Sub Main()

        Dim c1 As New C(42)
        Dim c2 As New C(1491)
        Dim f1 As New F()

        Dim d As D

        ' Instance method with one argument of type C.
        Dim cmi1 As MethodInfo = GetType(C).GetMethod("M1")
        ' Instance method with no arguments.
        Dim cmi2 As MethodInfo = GetType(C).GetMethod("M2")
        ' Shared method with one argument of type C.
        Dim cmi3 As MethodInfo = GetType(C).GetMethod("M3")
        ' Shared method with two arguments of type C.
        Dim cmi4 As MethodInfo = GetType(C).GetMethod("M4")

        ' Instance method with one argument of type C.
        Dim fmi1 As MethodInfo = GetType(F).GetMethod("M1")
        ' Shared method with one argument of type C.
        Dim fmi3 As MethodInfo = GetType(F).GetMethod("M3")
        ' Shared method with an argument of type F and an 
        ' argument of type C.
        Dim fmi4 As MethodInfo = GetType(F).GetMethod("M4")

        Console.WriteLine(vbLf & "An instance method on any type, with an argument of type C.")
        ' D can represent any instance method that exactly matches its
        ' signature. Methods on C and F are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi1), D)
        d(c2)
        d = CType([Delegate].CreateDelegate(GetType(D), f1, fmi1), D)
        d(c2)

        Console.WriteLine(vbLf & "An instance method on C with no arguments.")
        ' D can represent an instance method on C that has no arguments;
        ' in this case, the argument of D represents the hidden first
        ' argument of any instance method. The delegate acts like a 
        ' Shared method, and an instance of C must be passed each time
        ' it is invoked.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi2), D)
        d(c1)

        Console.WriteLine(vbLf & "A Shared method on any type, with an argument of type C.")
        ' D can represent any Shared method with the same signature.
        ' Methods on F and C are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi3), D)
        d(c1)
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, fmi3), D)
        d(c1)

        Console.WriteLine(vbLf & "A Shared method on any type, with an argument of")
        Console.WriteLine("    that type and an argument of type C.")
        ' D can represent any Shared method with one argument of the
        ' type the method belongs and a second argument of type C.
        ' In this case, the method is closed over the instance of
        ' supplied for the its first argument, and acts like an instance
        ' method. Methods on F and C are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi4), D)
        d(c2)
        Dim test As [Delegate] =
            [Delegate].CreateDelegate(GetType(D), f1, fmi4, False)

        ' This final example specifies False for throwOnBindFailure 
        ' in the call to CreateDelegate, so the variable 'test'
        ' contains Nothing if the method fails to bind (for 
        ' example, if fmi4 happened to represent a method of  
        ' some class other than F).
        '
        If test IsNot Nothing Then
            d = CType(test, D)
            d(c2)
        End If

    End Sub
End Class

' This code example produces the following output:
'
'An instance method on any type, with an argument of type C.
'Instance method M1(c As C) on C:  this.id = 42, c.ID = 1491
'Instance method M1(c As C) on F:  c.ID = 1491
'
'An instance method on C with no arguments.
'Instance method M2() on C:  this.id = 42
'
'A Shared method on any type, with an argument of type C.
'Shared method M3(c As C) on C:  c.ID = 42
'Shared method M3(c As C) on F:  c.ID = 42
'
'A Shared method on any type, with an argument of
'    that type and an argument of type C.
'Shared method M4(c1 As C, c2 As C) on C:  c1.ID = 42, c2.ID = 1491
'Shared method M4(f As F, c As C) on F:  c.ID = 1491
'

Ayrıca bkz.

Şunlara uygulanır

CreateDelegate(Type, Type, String, Boolean, Boolean)

Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs

Belirtilen sınıfın belirtilen statik yöntemini temsil eden belirtilen türde, belirtilen büyük/küçük harf duyarlılığı ve bağlama hatasında belirtilen davranış ile bir temsilci oluşturur.

public:
 static Delegate ^ CreateDelegate(Type ^ type, Type ^ target, System::String ^ method, bool ignoreCase, bool throwOnBindFailure);
public static Delegate? CreateDelegate(Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The target method might be removed")]
public static Delegate? CreateDelegate(Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure);
public static Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure);
static member CreateDelegate : Type * Type * string * bool * bool -> Delegate
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The target method might be removed")>]
static member CreateDelegate : Type * Type * string * bool * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Type, method As String, ignoreCase As Boolean, throwOnBindFailure As Boolean) As Delegate

Parametreler

type
Type

Type Oluşturulacak temsilci.

target
Type

Type uygulayan sınıfını temsil edenmethod.

method
String

Temsilcinin temsil etmek üzere olduğu statik yöntemin adı.

ignoreCase
Boolean

Yöntemin adı karşılaştırılırken büyük/küçük harf yoksayılıp yoksayılmayacağını gösteren Boole değeri.

throwOnBindFailure
Boolean

true bağlanamıyorsa method bir özel durum oluşturur; aksi takdirde , false.

Döndürülenler

Belirtilen sınıfın belirtilen statik yöntemini temsil eden belirtilen türün temsilcisi.

Öznitelikler

Özel durumlar

type, null'e eşittir.

-veya-

target, null'e eşittir.

-veya-

method, null'e eşittir.

type devralmıyor MulticastDelegate.

-veya-

type bir RuntimeTypedeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

-veya-

target bir RuntimeTypedeğildir.

-veya-

target açık bir genel türdür. Yani, özelliği ContainsGenericParameters şeklindedir true.

-veya-

method bir static yöntemi değildir (Visual Basic'de Shared yöntemi).

-veya-

method bağlanamıyor, örneğin bulunamadığı ve throwOnBindFailure olduğu trueiçin.

Invoke yöntemi type bulunamadı.

Çağıranın erişimi methodiçin gerekli izinlere sahip değil.

Açıklamalar

Bu yöntem yalnızca statik yöntemler için temsilciler oluşturur. Örnek yöntemi, sınıfın bir örneğiyle ilişkilendirilmiş bir yöntemdir; statik yöntem, sınıfın kendisiyle ilişkili bir yöntemdir.

Ayrıca bkz.

Şunlara uygulanır

CreateDelegate(Type, MethodInfo, Boolean)

Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs
Kaynak:
Delegate.CoreCLR.cs

Belirtilen statik yöntemi temsil etmek için belirtilen türün bir temsilcisini oluşturur ve bağlanma hatasında belirtilen davranış gösterilir.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Reflection::MethodInfo ^ method, bool throwOnBindFailure);
public static Delegate? CreateDelegate(Type type, System.Reflection.MethodInfo method, bool throwOnBindFailure);
public static Delegate CreateDelegate(Type type, System.Reflection.MethodInfo method, bool throwOnBindFailure);
static member CreateDelegate : Type * System.Reflection.MethodInfo * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, method As MethodInfo, throwOnBindFailure As Boolean) As Delegate

Parametreler

type
Type

Type Oluşturulacak temsilci.

method
MethodInfo

Temsilcinin MethodInfo temsil etmek üzere olduğu statik veya örnek yöntemini açıklayan.

throwOnBindFailure
Boolean

true bağlanamıyorsa method bir özel durum oluşturur; aksi takdirde , false.

Döndürülenler

Belirtilen statik yöntemi temsil etmek için belirtilen türün temsilcisi.

Özel durumlar

type, null'e eşittir.

-veya-

method, null'e eşittir.

type devralmıyor MulticastDelegate.

-veya-

type bir RuntimeTypedeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

-veya-

method bağlanamaz ve throwOnBindFailure şeklindedir true.

-veya-

method bir RuntimeMethodInfodeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

Invoke yöntemi type bulunamadı.

Çağıranın erişimi methodiçin gerekli izinlere sahip değil.

Örnekler

Bu bölüm iki kod örneği içerir. İlk örnekte, bu yöntem aşırı yüklemesiyle oluşturulabilecek iki tür temsilci gösterilmektedir: örnek yöntemi üzerinden açma ve statik bir yöntem üzerinden açma.

İkinci kod örneği uyumlu parametre türlerini ve dönüş türlerini gösterir.

Örnek 1

Aşağıdaki kod örneğinde, CreateDelegate yönteminin bu aşırı yüklemesi kullanılarak temsilci oluşturmanın iki yolu gösterilmektedir.

Note

CreateDelegate yönteminin bir MethodInfo belirten ancak ilk bağımsız değişkeni belirtmeyen iki aşırı yüklemesi vardır; işlevleri aynıdır, ancak biri bağlama hatasının atılıp atılmayacağını belirtmenize olanak tanır ve diğeri her zaman atar. Bu kod örneği her iki aşırı yüklemeyi de kullanır.

Örnek, bir sınıf C, statik bir metot M2 ve bir örnek metot M1ile iki temsilci türü bildirir: D1, bir C örneği ve bir dize alır; D2 ise bir dize alır.

Example adlı ikinci sınıf, temsilcileri oluşturan kodu içerir.

  • D1örnek yöntemi için açık örnek yöntemini temsil eden M1türünde bir temsilci oluşturulur. Temsilci çağrıldığında bir örnek geçirilmelidir.
  • D2statik yöntemi için açık statik yöntemi temsil eden M2türünde bir temsilci oluşturulur.
using System;
using System.Reflection;

// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
//
public delegate void D1(C c, string s);
public delegate void D2(string s);
public delegate void D3();

// A sample class with an instance method and a static method.
//
public class C
{
    private int id;
    public C(int id) { this.id = id; }

    public void M1(string s) =>
        Console.WriteLine($"Instance method M1 on C:  id = {this.id}, s = {s}");

    public static void M2(string s)
    {
        Console.WriteLine($"Static method M2 on C:  s = {s}");
    }
}

public class Example2
{
    public static void Main()
    {
        C c1 = new C(42);

        // Get a MethodInfo for each method.
        //
        MethodInfo mi1 = typeof(C).GetMethod("M1",
            BindingFlags.Public | BindingFlags.Instance);
        MethodInfo mi2 = typeof(C).GetMethod("M2",
            BindingFlags.Public | BindingFlags.Static);

        D1 d1;
        D2 d2;
        D3 d3;

        Console.WriteLine("\nAn instance method closed over C.");
        // In this case, the delegate and the
        // method must have the same list of argument types; use
        // delegate type D2 with instance method M1.
        //
        Delegate test =
            Delegate.CreateDelegate(typeof(D2), c1, mi1, false);

        // Because false was specified for throwOnBindFailure
        // in the call to CreateDelegate, the variable 'test'
        // contains null if the method fails to bind (for
        // example, if mi1 happened to represent a method of
        // some class other than C).
        //
        if (test != null)
        {
            d2 = (D2)test;

            // The same instance of C is used every time the
            // delegate is invoked.
            d2("Hello, World!");
            d2("Hi, Mom!");
        }

        Console.WriteLine("\nAn open instance method.");
        // In this case, the delegate has one more
        // argument than the instance method; this argument comes
        // at the beginning, and represents the hidden instance
        // argument of the instance method. Use delegate type D1
        // with instance method M1.
        //
        d1 = (D1)Delegate.CreateDelegate(typeof(D1), null, mi1);

        // An instance of C must be passed in each time the
        // delegate is invoked.
        //
        d1(c1, "Hello, World!");
        d1(new C(5280), "Hi, Mom!");

        Console.WriteLine("\nAn open static method.");
        // In this case, the delegate and the method must
        // have the same list of argument types; use delegate type
        // D2 with static method M2.
        //
        d2 = (D2)Delegate.CreateDelegate(typeof(D2), null, mi2);

        // No instances of C are involved, because this is a static
        // method.
        //
        d2("Hello, World!");
        d2("Hi, Mom!");

        Console.WriteLine("\nA static method closed over the first argument (String).");
        // The delegate must omit the first argument of the method.
        // A string is passed as the firstArgument parameter, and
        // the delegate is bound to this string. Use delegate type
        // D3 with static method M2.
        //
        d3 = (D3)Delegate.CreateDelegate(typeof(D3),
            "Hello, World!", mi2);

        // Each time the delegate is invoked, the same string is
        // used.
        d3();
    }
}

/* This code example produces the following output:

An instance method closed over C.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 42, s = Hi, Mom!

An open instance method.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 5280, s = Hi, Mom!

An open static method.
Static method M2 on C:  s = Hello, World!
Static method M2 on C:  s = Hi, Mom!

A static method closed over the first argument (String).
Static method M2 on C:  s = Hello, World!
 */
open System
open System.Reflection

// A sample class with an instance method and a static method.
type C(id) =
    member _.M1(s) =
        printfn $"Instance method M1 on C:  id = %i{id}, s = %s{s}"

    static member M2(s) =
        printfn $"Static method M2 on C:  s = %s{s}"
    
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
type D1 = delegate of C * string -> unit
type D2 = delegate of string -> unit
type D3 = delegate of unit -> unit

let c1 = C 42

// Get a MethodInfo for each method.
//
let mi1 = typeof<C>.GetMethod("M1", BindingFlags.Public ||| BindingFlags.Instance)
let mi2 = typeof<C>.GetMethod("M2", BindingFlags.Public ||| BindingFlags.Static)

printfn "\nAn instance method closed over C."

// In this case, the delegate and the
// method must have the same list of argument types use
// delegate type D2 with instance method M1.
let test = Delegate.CreateDelegate(typeof<D2>, c1, mi1, false)

// Because false was specified for throwOnBindFailure
// in the call to CreateDelegate, the variable 'test'
// contains null if the method fails to bind (for
// example, if mi1 happened to represent a method of
// some class other than C).
if test <> null then
    let d2 = test :?> D2

    // The same instance of C is used every time the
    // delegate is invoked.
    d2.Invoke "Hello, World!"
    d2.Invoke "Hi, Mom!"

printfn "\nAn open instance method."

// In this case, the delegate has one more
// argument than the instance method this argument comes
// at the beginning, and represents the hidden instance
// argument of the instance method. Use delegate type D1
// with instance method M1.
let d1 = Delegate.CreateDelegate(typeof<D1>, null, mi1) :?> D1

// An instance of C must be passed in each time the
// delegate is invoked.
d1.Invoke(c1, "Hello, World!")
d1.Invoke(C 5280, "Hi, Mom!")

printfn "\nAn open static method."
// In this case, the delegate and the method must
// have the same list of argument types use delegate type
// D2 with static method M2.
let d2 = Delegate.CreateDelegate(typeof<D2>, null, mi2) :?> D2

// No instances of C are involved, because this is a static
// method.
d2.Invoke "Hello, World!"
d2.Invoke "Hi, Mom!"

printfn "\nA static method closed over the first argument (String)."
// The delegate must omit the first argument of the method.
// A string is passed as the firstArgument parameter, and
// the delegate is bound to this string. Use delegate type
// D3 with static method M2.
let d3 = Delegate.CreateDelegate(typeof<D3>, "Hello, World!", mi2) :?> D3

// Each time the delegate is invoked, the same string is used.
d3.Invoke()

// This code example produces the following output:
//     An instance method closed over C.
//     Instance method M1 on C:  id = 42, s = Hello, World!
//     Instance method M1 on C:  id = 42, s = Hi, Mom!
//     
//     An open instance method.
//     Instance method M1 on C:  id = 42, s = Hello, World!
//     Instance method M1 on C:  id = 5280, s = Hi, Mom!
//     
//     An open static method.
//     Static method M2 on C:  s = Hello, World!
//     Static method M2 on C:  s = Hi, Mom!
//     
//     A static method closed over the first argument (String).
//     Static method M2 on C:  s = Hello, World!
Imports System.Reflection
Imports System.Security.Permissions

' Declare three delegate types for demonstrating the combinations
' of Shared versus instance methods and open versus closed
' delegates.
'
Public Delegate Sub D1(ByVal c As C2, ByVal s As String)
Public Delegate Sub D2(ByVal s As String)
Public Delegate Sub D3()

' A sample class with an instance method and a Shared method.
'
Public Class C2
    Private id As Integer
    Public Sub New(ByVal id As Integer)
        Me.id = id
    End Sub

    Public Sub M1(ByVal s As String)
        Console.WriteLine("Instance method M1 on C2:  id = {0}, s = {1}",
            Me.id, s)
    End Sub

    Public Shared Sub M2(ByVal s As String)
        Console.WriteLine("Shared method M2 on C2:  s = {0}", s)
    End Sub
End Class

Public Class Example2

    Public Shared Sub Main()

        Dim c1 As New C2(42)

        ' Get a MethodInfo for each method.
        '
        Dim mi1 As MethodInfo = GetType(C2).GetMethod("M1",
            BindingFlags.Public Or BindingFlags.Instance)
        Dim mi2 As MethodInfo = GetType(C2).GetMethod("M2",
            BindingFlags.Public Or BindingFlags.Static)

        Dim d1 As D1
        Dim d2 As D2
        Dim d3 As D3


        Console.WriteLine(vbLf & "An instance method closed over C2.")
        ' In this case, the delegate and the
        ' method must have the same list of argument types; use
        ' delegate type D2 with instance method M1.
        '
        Dim test As [Delegate] =
            [Delegate].CreateDelegate(GetType(D2), c1, mi1, False)

        ' Because False was specified for throwOnBindFailure 
        ' in the call to CreateDelegate, the variable 'test'
        ' contains Nothing if the method fails to bind (for 
        ' example, if mi1 happened to represent a method of 
        ' some class other than C2).
        '
        If test IsNot Nothing Then
            d2 = CType(test, D2)

            ' The same instance of C2 is used every time the
            ' delegate is invoked.
            d2("Hello, World!")
            d2("Hi, Mom!")
        End If


        Console.WriteLine(vbLf & "An open instance method.")
        ' In this case, the delegate has one more 
        ' argument than the instance method; this argument comes
        ' at the beginning, and represents the hidden instance
        ' argument of the instance method. Use delegate type D1
        ' with instance method M1.
        '
        d1 = CType([Delegate].CreateDelegate(GetType(D1), Nothing, mi1), D1)

        ' An instance of C2 must be passed in each time the 
        ' delegate is invoked.
        '
        d1(c1, "Hello, World!")
        d1(New C2(5280), "Hi, Mom!")


        Console.WriteLine(vbLf & "An open Shared method.")
        ' In this case, the delegate and the method must 
        ' have the same list of argument types; use delegate type
        ' D2 with Shared method M2.
        '
        d2 = CType([Delegate].CreateDelegate(GetType(D2), Nothing, mi2), D2)

        ' No instances of C2 are involved, because this is a Shared
        ' method. 
        '
        d2("Hello, World!")
        d2("Hi, Mom!")


        Console.WriteLine(vbLf & "A Shared method closed over the first argument (String).")
        ' The delegate must omit the first argument of the method.
        ' A string is passed as the firstArgument parameter, and 
        ' the delegate is bound to this string. Use delegate type 
        ' D3 with Shared method M2. 
        '
        d3 = CType([Delegate].CreateDelegate(GetType(D3), "Hello, World!", mi2), D3)

        ' Each time the delegate is invoked, the same string is
        ' used.
        d3()

    End Sub
End Class

' This code example produces the following output:
'
'An instance method closed over C2.
'Instance method M1 on C2:  id = 42, s = Hello, World!
'Instance method M1 on C2:  id = 42, s = Hi, Mom!
'
'An open instance method.
'Instance method M1 on C2:  id = 42, s = Hello, World!
'Instance method M1 on C2:  id = 5280, s = Hi, Mom!
'
'An open Shared method.
'Shared method M2 on C2:  s = Hello, World!
'Shared method M2 on C2:  s = Hi, Mom!
'
'A Shared method closed over the first argument (String).
'Shared method M2 on C2:  s = Hello, World!
'

Örnek 2

Aşağıdaki kod örneği, parametre türlerinin ve dönüş türlerinin uyumluluğunu gösterir.

Kod örneği, Base adlı bir temel sınıfı ve Derivedtüretilen Base adlı bir sınıfı tanımlar. Türetilen sınıfın static türünde bir parametresi ve Shareddönüş türüyle MyMethod adlı Base ( Visual Basic'teDerived) yöntemi vardır. Kod örneği, Example türünde bir parametresi ve Deriveddönüş türüne sahip Base adlı bir temsilci de tanımlar.

Kod örneği, Example adlı temsilcinin MyMethodyöntemini temsil etmek için kullanılabileceğini gösterir. Yöntemi temsilciye bağlanabilir çünkü:

  • Temsilcinin parametre türü (Derived), MyMethod'in parametre türünden daha sınırlayıcıdır (Base), bu yüzden temsilcinin bağımsız değişkeninin MyMethod'e aktarılması her zaman güvenlidir.
  • MyMethod (Derived) dönüş türü, temsilcinin parametre türünden daha kısıtlayıcıdır (Base), bu nedenle yöntemin dönüş türünü temsilcinin dönüş türüne atamak her zaman güvenlidir.

Kod örneği çıkış üretmez.

using System;
using System.Reflection;

// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
//
public class Base { }

public class Derived : Base
{
    // Define a static method to use in the demonstration. The method
    // takes an instance of Base and returns an instance of Derived.
    // For the purposes of the demonstration, it is not necessary for
    // the method to do anything useful.
    //
    public static Derived MyMethod(Base arg)
    {
        Base dummy = arg;
        return new Derived();
    }
}

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base Example5(Derived arg);

class Test
{
    public static void Main()
    {
        // The binding flags needed to retrieve MyMethod.
        BindingFlags flags = BindingFlags.Public | BindingFlags.Static;

        // Get a MethodInfo that represents MyMethod.
        MethodInfo minfo = typeof(Derived).GetMethod("MyMethod", flags);

        // Demonstrate contravariance of parameter types and covariance
        // of return types by using the delegate Example5 to represent
        // MyMethod. The delegate binds to the method because the
        // parameter of the delegate is more restrictive than the
        // parameter of the method (that is, the delegate accepts an
        // instance of Derived, which can always be safely passed to
        // a parameter of type Base), and the return type of MyMethod
        // is more restrictive than the return type of Example5 (that
        // is, the method returns an instance of Derived, which can
        // always be safely cast to type Base).
        //
        Example5 ex =
            (Example5)Delegate.CreateDelegate(typeof(Example5), minfo);

        // Execute MyMethod using the delegate Example5.
        //
        Base b = ex(new Derived());
    }
}
open System
open System.Reflection

// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
type Base() = class end

type Derived() =
    inherit Base()

    // Define a static method to use in the demonstration. The method
    // takes an instance of Base and returns an instance of Derived.
    // For the purposes of the demonstration, it is not necessary for
    // the method to do anything useful.
    static member MyMethod(arg: Base) =
        Derived()

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
type Example = delegate of Derived -> Base

// The binding flags needed to retrieve MyMethod.
let flags = BindingFlags.Public ||| BindingFlags.Static

// Get a MethodInfo that represents MyMethod.
let minfo = typeof<Derived>.GetMethod("MyMethod", flags)

// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
let ex = Delegate.CreateDelegate(typeof<Example>, minfo) :?> Example

// Execute MyMethod using the delegate Example.
let b = Derived() |> ex.Invoke
Imports System.Reflection

' Define two classes to use in the demonstration, a base class and 
' a class that derives from it.
'
Public Class Base
End Class

Public Class Derived
    Inherits Base

    ' Define a Shared method to use in the demonstration. The method 
    ' takes an instance of Base and returns an instance of Derived.  
    ' For the purposes of the demonstration, it is not necessary for 
    ' the method to do anything useful. 
    '
    Public Shared Function MyMethod(ByVal arg As Base) As Derived
        Dim dummy As Base = arg
        Return New Derived()
    End Function

End Class

' Define a delegate that takes an instance of Derived and returns an
' instance of Base.
'
Public Delegate Function Example(ByVal arg As Derived) As Base

Module Test

    Sub Main()

        ' The binding flags needed to retrieve MyMethod.
        Dim flags As BindingFlags = _
            BindingFlags.Public Or BindingFlags.Static

        ' Get a MethodInfo that represents MyMethod.
        Dim minfo As MethodInfo = _
            GetType(Derived).GetMethod("MyMethod", flags)

        ' Demonstrate contravariance of parameter types and covariance
        ' of return types by using the delegate Example to represent
        ' MyMethod. The delegate binds to the method because the
        ' parameter of the delegate is more restrictive than the 
        ' parameter of the method (that is, the delegate accepts an
        ' instance of Derived, which can always be safely passed to
        ' a parameter of type Base), and the return type of MyMethod
        ' is more restrictive than the return type of Example (that
        ' is, the method returns an instance of Derived, which can
        ' always be safely cast to type Base). 
        '
        Dim ex As Example = CType( _
            [Delegate].CreateDelegate(GetType(Example), minfo), _
            Example _
        )

        ' Execute MyMethod using the delegate Example.
        '        
        Dim b As Base = ex(New Derived())
    End Sub
End Module

Açıklamalar

Bu yöntem aşırı yüklemesi, açık statik yöntem temsilcileri ve açık örnek yöntemi temsilcileri, yani örnek yöntemlerinin gizli ilk bağımsız değişkenini kullanıma sunan temsilciler oluşturabilir. Ayrıntılı bir açıklama için, örnek veya statik yöntemler için açık veya kapalı temsilcilerin tüm birleşimlerini oluşturmanıza olanak tanıyan daha genel CreateDelegate(Type, Object, MethodInfo, Boolean) yöntem aşırı yüklemesine bakın.

Note

Bu durumda biraz daha hızlı olduğundan, temsilci ilk bağımsız değişkeni üzerinden kapatılmadığında bu yöntem aşırı yüklemesi kullanılmalıdır.

Ayrıca bkz.

Şunlara uygulanır

CreateDelegate(Type, Object, String)

Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs

Belirtilen sınıf örneğinde çağrılacak belirtilen örnek yöntemini temsil eden belirtilen türde bir temsilci oluşturur.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ target, System::String ^ method);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The target method might be removed")]
public static Delegate CreateDelegate(Type type, object target, string method);
public static Delegate CreateDelegate(Type type, object target, string method);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The target method might be removed")>]
static member CreateDelegate : Type * obj * string -> Delegate
static member CreateDelegate : Type * obj * string -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Object, method As String) As Delegate

Parametreler

type
Type

Type Oluşturulacak temsilci.

target
Object

Üzerinde çağrılan method sınıf örneği.

method
String

Temsilcinin temsil etmek üzere olduğu örnek yönteminin adı.

Döndürülenler

Belirtilen sınıf örneğinde çağrılacak belirtilen örnek yöntemini temsil eden belirtilen türde bir temsilci.

Öznitelikler

Özel durumlar

type, null'e eşittir.

-veya-

target, null'e eşittir.

-veya-

method, null'e eşittir.

type devralmıyor MulticastDelegate.

-veya-

type bir RuntimeTypedeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

-veya-

method bir örnek yöntemi değildir.

-veya-

method bağlanamıyor, örneğin bulunamadığından.

Invoke yöntemi type bulunamadı.

Çağıranın erişimi methodiçin gerekli izinlere sahip değil.

Açıklamalar

Bu yöntem yalnızca örnek yöntemleri için temsilciler oluşturur. Örnek yöntemi, sınıfın bir örneğiyle ilişkilendirilmiş bir yöntemdir; statik yöntem, sınıfın kendisiyle ilişkili bir yöntemdir.

Bu yöntem aşırı yüklemesi, için CreateDelegate(Type, Object, String, Boolean, Boolean) ve falseignoreCasedeğerini belirterek true yöntem aşırı yüklemesini throwOnBindFailure çağırmaya eşdeğerdir.

Ayrıca bkz.

Şunlara uygulanır

CreateDelegate(Type, Object, MethodInfo)

Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs

Belirtilen ilk bağımsız değişkenle belirtilen statik veya örnek yöntemini temsil eden belirtilen türde bir temsilci oluşturur.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ firstArgument, System::Reflection::MethodInfo ^ method);
public static Delegate CreateDelegate(Type type, object? firstArgument, System.Reflection.MethodInfo method);
public static Delegate CreateDelegate(Type type, object firstArgument, System.Reflection.MethodInfo method);
static member CreateDelegate : Type * obj * System.Reflection.MethodInfo -> Delegate
Public Shared Function CreateDelegate (type As Type, firstArgument As Object, method As MethodInfo) As Delegate

Parametreler

type
Type

Type Oluşturulacak temsilci.

firstArgument
Object

Temsilcinin bağlı olduğu nesne veya nullmethod olarak işlemek için static (Visual Basic'de Shared).

method
MethodInfo

Temsilcinin MethodInfo temsil etmek üzere olduğu statik veya örnek yöntemini açıklayan.

Döndürülenler

Belirtilen statik veya örnek yöntemini temsil eden belirtilen türün temsilcisi.

Özel durumlar

type, null'e eşittir.

-veya-

method, null'e eşittir.

type devralmıyor MulticastDelegate.

-veya-

type bir RuntimeTypedeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

-veya-

method bağlanamıyor.

-veya-

method bir RuntimeMethodInfodeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

Invoke yöntemi type bulunamadı.

Çağıranın erişimi methodiçin gerekli izinlere sahip değil.

Örnekler

Bu bölüm iki kod örneği içerir. İlk örnekte, bu yöntem aşırı yüklemesiyle oluşturulabilecek iki tür temsilci gösterilmektedir: örnek yöntemi üzerinden açma ve statik bir yöntem üzerinden açma.

İkinci kod örneği uyumlu parametre türlerini ve dönüş türlerini gösterir.

Örnek 1

Aşağıdaki kod örneğinde, CreateDelegate yönteminin bu aşırı yüklemesi kullanılarak temsilci oluşturmanın iki yolu gösterilmektedir.

Note

CreateDelegate yönteminin bir MethodInfo belirten ancak ilk bağımsız değişkeni belirtmeyen iki aşırı yüklemesi vardır; işlevleri aynıdır, ancak biri bağlama hatasının atılıp atılmayacağını belirtmenize olanak tanır ve diğeri her zaman atar. Bu kod örneği her iki aşırı yüklemeyi de kullanır.

Örnek, bir sınıf C, statik bir metot M2 ve bir örnek metot M1ile iki temsilci türü bildirir: D1, bir C örneği ve bir dize alır; D2 ise bir dize alır.

Example adlı ikinci sınıf, temsilcileri oluşturan kodu içerir.

  • D1örnek yöntemi için açık örnek yöntemini temsil eden M1türünde bir temsilci oluşturulur. Temsilci çağrıldığında bir örnek geçirilmelidir.
  • D2statik yöntemi için açık statik yöntemi temsil eden M2türünde bir temsilci oluşturulur.
using System;
using System.Reflection;

// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
//
public delegate void D1(C c, string s);
public delegate void D2(string s);
public delegate void D3();

// A sample class with an instance method and a static method.
//
public class C
{
    private int id;
    public C(int id) { this.id = id; }

    public void M1(string s) =>
        Console.WriteLine($"Instance method M1 on C:  id = {this.id}, s = {s}");

    public static void M2(string s)
    {
        Console.WriteLine($"Static method M2 on C:  s = {s}");
    }
}

public class Example2
{
    public static void Main()
    {
        C c1 = new C(42);

        // Get a MethodInfo for each method.
        //
        MethodInfo mi1 = typeof(C).GetMethod("M1",
            BindingFlags.Public | BindingFlags.Instance);
        MethodInfo mi2 = typeof(C).GetMethod("M2",
            BindingFlags.Public | BindingFlags.Static);

        D1 d1;
        D2 d2;
        D3 d3;

        Console.WriteLine("\nAn instance method closed over C.");
        // In this case, the delegate and the
        // method must have the same list of argument types; use
        // delegate type D2 with instance method M1.
        //
        Delegate test =
            Delegate.CreateDelegate(typeof(D2), c1, mi1, false);

        // Because false was specified for throwOnBindFailure
        // in the call to CreateDelegate, the variable 'test'
        // contains null if the method fails to bind (for
        // example, if mi1 happened to represent a method of
        // some class other than C).
        //
        if (test != null)
        {
            d2 = (D2)test;

            // The same instance of C is used every time the
            // delegate is invoked.
            d2("Hello, World!");
            d2("Hi, Mom!");
        }

        Console.WriteLine("\nAn open instance method.");
        // In this case, the delegate has one more
        // argument than the instance method; this argument comes
        // at the beginning, and represents the hidden instance
        // argument of the instance method. Use delegate type D1
        // with instance method M1.
        //
        d1 = (D1)Delegate.CreateDelegate(typeof(D1), null, mi1);

        // An instance of C must be passed in each time the
        // delegate is invoked.
        //
        d1(c1, "Hello, World!");
        d1(new C(5280), "Hi, Mom!");

        Console.WriteLine("\nAn open static method.");
        // In this case, the delegate and the method must
        // have the same list of argument types; use delegate type
        // D2 with static method M2.
        //
        d2 = (D2)Delegate.CreateDelegate(typeof(D2), null, mi2);

        // No instances of C are involved, because this is a static
        // method.
        //
        d2("Hello, World!");
        d2("Hi, Mom!");

        Console.WriteLine("\nA static method closed over the first argument (String).");
        // The delegate must omit the first argument of the method.
        // A string is passed as the firstArgument parameter, and
        // the delegate is bound to this string. Use delegate type
        // D3 with static method M2.
        //
        d3 = (D3)Delegate.CreateDelegate(typeof(D3),
            "Hello, World!", mi2);

        // Each time the delegate is invoked, the same string is
        // used.
        d3();
    }
}

/* This code example produces the following output:

An instance method closed over C.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 42, s = Hi, Mom!

An open instance method.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 5280, s = Hi, Mom!

An open static method.
Static method M2 on C:  s = Hello, World!
Static method M2 on C:  s = Hi, Mom!

A static method closed over the first argument (String).
Static method M2 on C:  s = Hello, World!
 */
open System
open System.Reflection

// A sample class with an instance method and a static method.
type C(id) =
    member _.M1(s) =
        printfn $"Instance method M1 on C:  id = %i{id}, s = %s{s}"

    static member M2(s) =
        printfn $"Static method M2 on C:  s = %s{s}"
    
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
type D1 = delegate of C * string -> unit
type D2 = delegate of string -> unit
type D3 = delegate of unit -> unit

let c1 = C 42

// Get a MethodInfo for each method.
//
let mi1 = typeof<C>.GetMethod("M1", BindingFlags.Public ||| BindingFlags.Instance)
let mi2 = typeof<C>.GetMethod("M2", BindingFlags.Public ||| BindingFlags.Static)

printfn "\nAn instance method closed over C."

// In this case, the delegate and the
// method must have the same list of argument types use
// delegate type D2 with instance method M1.
let test = Delegate.CreateDelegate(typeof<D2>, c1, mi1, false)

// Because false was specified for throwOnBindFailure
// in the call to CreateDelegate, the variable 'test'
// contains null if the method fails to bind (for
// example, if mi1 happened to represent a method of
// some class other than C).
if test <> null then
    let d2 = test :?> D2

    // The same instance of C is used every time the
    // delegate is invoked.
    d2.Invoke "Hello, World!"
    d2.Invoke "Hi, Mom!"

printfn "\nAn open instance method."

// In this case, the delegate has one more
// argument than the instance method this argument comes
// at the beginning, and represents the hidden instance
// argument of the instance method. Use delegate type D1
// with instance method M1.
let d1 = Delegate.CreateDelegate(typeof<D1>, null, mi1) :?> D1

// An instance of C must be passed in each time the
// delegate is invoked.
d1.Invoke(c1, "Hello, World!")
d1.Invoke(C 5280, "Hi, Mom!")

printfn "\nAn open static method."
// In this case, the delegate and the method must
// have the same list of argument types use delegate type
// D2 with static method M2.
let d2 = Delegate.CreateDelegate(typeof<D2>, null, mi2) :?> D2

// No instances of C are involved, because this is a static
// method.
d2.Invoke "Hello, World!"
d2.Invoke "Hi, Mom!"

printfn "\nA static method closed over the first argument (String)."
// The delegate must omit the first argument of the method.
// A string is passed as the firstArgument parameter, and
// the delegate is bound to this string. Use delegate type
// D3 with static method M2.
let d3 = Delegate.CreateDelegate(typeof<D3>, "Hello, World!", mi2) :?> D3

// Each time the delegate is invoked, the same string is used.
d3.Invoke()

// This code example produces the following output:
//     An instance method closed over C.
//     Instance method M1 on C:  id = 42, s = Hello, World!
//     Instance method M1 on C:  id = 42, s = Hi, Mom!
//     
//     An open instance method.
//     Instance method M1 on C:  id = 42, s = Hello, World!
//     Instance method M1 on C:  id = 5280, s = Hi, Mom!
//     
//     An open static method.
//     Static method M2 on C:  s = Hello, World!
//     Static method M2 on C:  s = Hi, Mom!
//     
//     A static method closed over the first argument (String).
//     Static method M2 on C:  s = Hello, World!
Imports System.Reflection
Imports System.Security.Permissions

' Declare three delegate types for demonstrating the combinations
' of Shared versus instance methods and open versus closed
' delegates.
'
Public Delegate Sub D1(ByVal c As C2, ByVal s As String)
Public Delegate Sub D2(ByVal s As String)
Public Delegate Sub D3()

' A sample class with an instance method and a Shared method.
'
Public Class C2
    Private id As Integer
    Public Sub New(ByVal id As Integer)
        Me.id = id
    End Sub

    Public Sub M1(ByVal s As String)
        Console.WriteLine("Instance method M1 on C2:  id = {0}, s = {1}",
            Me.id, s)
    End Sub

    Public Shared Sub M2(ByVal s As String)
        Console.WriteLine("Shared method M2 on C2:  s = {0}", s)
    End Sub
End Class

Public Class Example2

    Public Shared Sub Main()

        Dim c1 As New C2(42)

        ' Get a MethodInfo for each method.
        '
        Dim mi1 As MethodInfo = GetType(C2).GetMethod("M1",
            BindingFlags.Public Or BindingFlags.Instance)
        Dim mi2 As MethodInfo = GetType(C2).GetMethod("M2",
            BindingFlags.Public Or BindingFlags.Static)

        Dim d1 As D1
        Dim d2 As D2
        Dim d3 As D3


        Console.WriteLine(vbLf & "An instance method closed over C2.")
        ' In this case, the delegate and the
        ' method must have the same list of argument types; use
        ' delegate type D2 with instance method M1.
        '
        Dim test As [Delegate] =
            [Delegate].CreateDelegate(GetType(D2), c1, mi1, False)

        ' Because False was specified for throwOnBindFailure 
        ' in the call to CreateDelegate, the variable 'test'
        ' contains Nothing if the method fails to bind (for 
        ' example, if mi1 happened to represent a method of 
        ' some class other than C2).
        '
        If test IsNot Nothing Then
            d2 = CType(test, D2)

            ' The same instance of C2 is used every time the
            ' delegate is invoked.
            d2("Hello, World!")
            d2("Hi, Mom!")
        End If


        Console.WriteLine(vbLf & "An open instance method.")
        ' In this case, the delegate has one more 
        ' argument than the instance method; this argument comes
        ' at the beginning, and represents the hidden instance
        ' argument of the instance method. Use delegate type D1
        ' with instance method M1.
        '
        d1 = CType([Delegate].CreateDelegate(GetType(D1), Nothing, mi1), D1)

        ' An instance of C2 must be passed in each time the 
        ' delegate is invoked.
        '
        d1(c1, "Hello, World!")
        d1(New C2(5280), "Hi, Mom!")


        Console.WriteLine(vbLf & "An open Shared method.")
        ' In this case, the delegate and the method must 
        ' have the same list of argument types; use delegate type
        ' D2 with Shared method M2.
        '
        d2 = CType([Delegate].CreateDelegate(GetType(D2), Nothing, mi2), D2)

        ' No instances of C2 are involved, because this is a Shared
        ' method. 
        '
        d2("Hello, World!")
        d2("Hi, Mom!")


        Console.WriteLine(vbLf & "A Shared method closed over the first argument (String).")
        ' The delegate must omit the first argument of the method.
        ' A string is passed as the firstArgument parameter, and 
        ' the delegate is bound to this string. Use delegate type 
        ' D3 with Shared method M2. 
        '
        d3 = CType([Delegate].CreateDelegate(GetType(D3), "Hello, World!", mi2), D3)

        ' Each time the delegate is invoked, the same string is
        ' used.
        d3()

    End Sub
End Class

' This code example produces the following output:
'
'An instance method closed over C2.
'Instance method M1 on C2:  id = 42, s = Hello, World!
'Instance method M1 on C2:  id = 42, s = Hi, Mom!
'
'An open instance method.
'Instance method M1 on C2:  id = 42, s = Hello, World!
'Instance method M1 on C2:  id = 5280, s = Hi, Mom!
'
'An open Shared method.
'Shared method M2 on C2:  s = Hello, World!
'Shared method M2 on C2:  s = Hi, Mom!
'
'A Shared method closed over the first argument (String).
'Shared method M2 on C2:  s = Hello, World!
'

Örnek 2

Aşağıdaki kod örneği, parametre türlerinin ve dönüş türlerinin uyumluluğunu gösterir.

Kod örneği, Base adlı bir temel sınıfı ve Derivedtüretilen Base adlı bir sınıfı tanımlar. Türetilen sınıfın static türünde bir parametresi ve Shareddönüş türüyle MyMethod adlı Base ( Visual Basic'teDerived) yöntemi vardır. Kod örneği, Example türünde bir parametresi ve Deriveddönüş türüne sahip Base adlı bir temsilci de tanımlar.

Kod örneği, Example adlı temsilcinin MyMethodyöntemini temsil etmek için kullanılabileceğini gösterir. Yöntemi temsilciye bağlanabilir çünkü:

  • Temsilcinin parametre türü (Derived), MyMethod'in parametre türünden daha sınırlayıcıdır (Base), bu yüzden temsilcinin bağımsız değişkeninin MyMethod'e aktarılması her zaman güvenlidir.
  • MyMethod (Derived) dönüş türü, temsilcinin parametre türünden daha kısıtlayıcıdır (Base), bu nedenle yöntemin dönüş türünü temsilcinin dönüş türüne atamak her zaman güvenlidir.

Kod örneği çıkış üretmez.

using System;
using System.Reflection;

// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
//
public class Base { }

public class Derived : Base
{
    // Define a static method to use in the demonstration. The method
    // takes an instance of Base and returns an instance of Derived.
    // For the purposes of the demonstration, it is not necessary for
    // the method to do anything useful.
    //
    public static Derived MyMethod(Base arg)
    {
        Base dummy = arg;
        return new Derived();
    }
}

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base Example5(Derived arg);

class Test
{
    public static void Main()
    {
        // The binding flags needed to retrieve MyMethod.
        BindingFlags flags = BindingFlags.Public | BindingFlags.Static;

        // Get a MethodInfo that represents MyMethod.
        MethodInfo minfo = typeof(Derived).GetMethod("MyMethod", flags);

        // Demonstrate contravariance of parameter types and covariance
        // of return types by using the delegate Example5 to represent
        // MyMethod. The delegate binds to the method because the
        // parameter of the delegate is more restrictive than the
        // parameter of the method (that is, the delegate accepts an
        // instance of Derived, which can always be safely passed to
        // a parameter of type Base), and the return type of MyMethod
        // is more restrictive than the return type of Example5 (that
        // is, the method returns an instance of Derived, which can
        // always be safely cast to type Base).
        //
        Example5 ex =
            (Example5)Delegate.CreateDelegate(typeof(Example5), minfo);

        // Execute MyMethod using the delegate Example5.
        //
        Base b = ex(new Derived());
    }
}
open System
open System.Reflection

// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
type Base() = class end

type Derived() =
    inherit Base()

    // Define a static method to use in the demonstration. The method
    // takes an instance of Base and returns an instance of Derived.
    // For the purposes of the demonstration, it is not necessary for
    // the method to do anything useful.
    static member MyMethod(arg: Base) =
        Derived()

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
type Example = delegate of Derived -> Base

// The binding flags needed to retrieve MyMethod.
let flags = BindingFlags.Public ||| BindingFlags.Static

// Get a MethodInfo that represents MyMethod.
let minfo = typeof<Derived>.GetMethod("MyMethod", flags)

// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
let ex = Delegate.CreateDelegate(typeof<Example>, minfo) :?> Example

// Execute MyMethod using the delegate Example.
let b = Derived() |> ex.Invoke
Imports System.Reflection

' Define two classes to use in the demonstration, a base class and 
' a class that derives from it.
'
Public Class Base
End Class

Public Class Derived
    Inherits Base

    ' Define a Shared method to use in the demonstration. The method 
    ' takes an instance of Base and returns an instance of Derived.  
    ' For the purposes of the demonstration, it is not necessary for 
    ' the method to do anything useful. 
    '
    Public Shared Function MyMethod(ByVal arg As Base) As Derived
        Dim dummy As Base = arg
        Return New Derived()
    End Function

End Class

' Define a delegate that takes an instance of Derived and returns an
' instance of Base.
'
Public Delegate Function Example(ByVal arg As Derived) As Base

Module Test

    Sub Main()

        ' The binding flags needed to retrieve MyMethod.
        Dim flags As BindingFlags = _
            BindingFlags.Public Or BindingFlags.Static

        ' Get a MethodInfo that represents MyMethod.
        Dim minfo As MethodInfo = _
            GetType(Derived).GetMethod("MyMethod", flags)

        ' Demonstrate contravariance of parameter types and covariance
        ' of return types by using the delegate Example to represent
        ' MyMethod. The delegate binds to the method because the
        ' parameter of the delegate is more restrictive than the 
        ' parameter of the method (that is, the delegate accepts an
        ' instance of Derived, which can always be safely passed to
        ' a parameter of type Base), and the return type of MyMethod
        ' is more restrictive than the return type of Example (that
        ' is, the method returns an instance of Derived, which can
        ' always be safely cast to type Base). 
        '
        Dim ex As Example = CType( _
            [Delegate].CreateDelegate(GetType(Example), minfo), _
            Example _
        )

        ' Execute MyMethod using the delegate Example.
        '        
        Dim b As Base = ex(New Derived())
    End Sub
End Module

CreateDelegate(Type, Object, MethodInfo) ve CreateDelegate(Type, Object, MethodInfo, Boolean) yöntemleri

Bu iki aşırı yüklemenin işlevselliği aynıdır, ancak biri bağlama hatasında atılıp atılmayacağını belirtmenize olanak tanır ve diğeri her zaman atar.

Temsilci türü ve yöntemi uyumlu dönüş türlerine sahip olmalıdır. Yani, method dönüş türü typedönüş türüne atanabilir olmalıdır.

firstArgument, bu aşırı yüklemelerin ikinci parametresi, temsilcinin temsil ettiği yöntemin ilk bağımsız değişkenidir. firstArgument sağlanırsa, temsilci her çağrıldığında firstArgumentfirstArgument'e iletilir; 'nin temsilciye bağlı olduğu ve temsilcinin ilk bağımsız değişkeni üzerinde işlevsel olarak kapandığı söylenir. method static ise (Visual Basic'teShared), temsilci çağrılırken sağlanan bağımsız değişken listesi ilk parametre dışındaki tüm parametreleri içerir; method bir örnek yöntemiyse, gizli örnek parametresine (C# dilinde firstArgument veya Visual Basic'teki this tarafından temsil edilen) Me geçirilir.

firstArgument sağlanırsa, method ilk parametresi bir başvuru türü olmalı ve firstArgument bu türle uyumlu olmalıdır.

Important

method static (Visual Basic'teShared) ve ilk parametresi Object veya ValueTypetüründeyse, firstArgument bir değer türü olabilir. Bu durumda firstArgument otomatik olarak kutulanır. C# veya Visual Basic işlev çağrısında olduğu gibi diğer bağımsız değişkenler için otomatik kutulama gerçekleşmez.

firstArgument null referans ve method bir örnek metot ise, sonuç delege tipi type ve methodimzalarına bağlıdır.

  • type imzası açıkça methodgizli ilk parametresini içeriyorsa, temsilcinin açık bir örnek yöntemini temsil ettiğini söylenir. Temsilci çağrıldığında, bağımsız değişken listesindeki ilk bağımsız değişken methodgizli örnek parametresine geçirilir.
  • method ve type imzaları eşleşiyorsa (yani, tüm parametre türleri uyumludur), temsilcinin null referansı üzerinde kapatıldığı söylenir. Temsilciyi çağırmak, null örnekte bir örnek yöntemini çağırmak gibidir ve bu özellikle yararlı bir işlem değildir.

firstArgument null başvuruysa ve method statikse, sonuç temsilci türü type ve methodimzalarına bağlıdır:

  • method ve type imzası eşleşiyorsa (diğer bir ifadeyle tüm parametre türleri uyumludur), temsilcinin açık statik bir yöntemi temsil olduğu söylenir. Bu, statik yöntemler için en yaygın durumdur. Bu durumda, CreateDelegate(Type, MethodInfo) metot aşırı yüklemesini kullanarak biraz daha iyi bir performans elde edebilirsiniz.
  • type imzası, method'in ikinci parametresiyle başlıyorsa ve geri kalan parametre türleri uyumluysa, temsilcinin null bir referans üzerinde kapatıldığı söylenir. Temsilci çağrıldığında, method'ın ilk parametresine boş bir referans geçirilir.

Example

Aşağıdaki kod örneği, tek bir temsilci türünün gösterebileceği tüm yöntemleri gösterir: örnek yöntemi üzerinden kapatılır, örnek yöntemi üzerinden açılır, statik yöntem üzerinden açılır ve statik yöntem üzerinden kapatılır.

Kod örneği, C ve Folmak üzere iki sınıfı ve Dtüründe bir bağımsız değişkeni olan bir temsilci türü C tanımlar. Sınıfların, M1, M3ve M4ile eşleşen statik ve örnek yöntemleri vardır ve sınıf C'ün, bağımsız değişkeni olmayan bir örnek yöntemi M2 sahiptir.

Example adlı üçüncü sınıf, temsilcileri oluşturan kodu içerir.

  • Temsilciler, M1 örnek yöntemi ile C ve Ftürleri için oluşturulur; her biri ilgili türün bir örneğine göre kapatılır. M1 yönteminin C türü, bağlı örneğin ve bağımsız değişkenin ID özelliklerini görüntüler.
  • M2türünde yöntem C için bir temsilci oluşturulur. Bu, temsilci bağımsız değişkeninin örnek yöntemindeki gizli ilk bağımsız değişkeni temsil ettiği açık örnek temsilcisidir. Yöntemin başka parametresi yok. Statik bir yöntemmiş gibi çağrılır.
  • Temsilciler, M3 statik yöntemi için C türü ve Ftürü olarak oluşturulur; bunlar açık statik temsilcilerdir.
  • Son olarak, M4 türüne ve Ctürüne ait olan statik yöntem F için temsilciler oluşturulur; her yöntemin bildirim türü ilk bağımsız değişken olarak görev yapar ve türün bir örneği sağlandığı için, temsilciler ilk bağımsız değişkenleri üzerine kapatılır. M4 yönteminin C türü, bağlı örneğin ve bağımsız değişkenin ID özelliklerini görüntüler.
using System;
using System.Reflection;

// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
//
public delegate void D(C1 c);

// Declare two sample classes, C1 and F. Class C1 has an ID
// property so instances can be identified.
//
public class C1
{
    private int id;
    public int ID => id;
    public C1(int id) => this.id = id;

    public void M1(C1 c)
    {
        Console.WriteLine("Instance method M1(C1 c) on C1:  this.id = {0}, c.ID = {1}",
            this.id, c.ID);
    }

    public void M2()
    {
        Console.WriteLine($"Instance method M2() on C1:  this.id = {this.id}");
    }

    public static void M3(C1 c)
    {
        Console.WriteLine($"Static method M3(C1 c) on C1:  c.ID = {c.ID}");
    }

    public static void M4(C1 c1, C1 c2)
    {
        Console.WriteLine("Static method M4(C1 c1, C1 c2) on C1:  c1.ID = {0}, c2.ID = {1}",
            c1.ID, c2.ID);
    }
}

public class F
{
    public void M1(C1 c)
    {
        Console.WriteLine($"Instance method M1(C1 c) on F:  c.ID = {c.ID}");
    }

    public static void M3(C1 c)
    {
        Console.WriteLine($"Static method M3(C1 c) on F:  c.ID = {c.ID}");
    }

    public static void M4(F f, C1 c)
    {
        Console.WriteLine($"Static method M4(F f, C1 c) on F:  c.ID = {c.ID}");
    }
}

public class Example
{
    public static void Main()
    {
        C1 c1 = new (42);
        C1 c2 = new (1491);
        F f1 = new ();

        D d;

        // Instance method with one argument of type C1.
        MethodInfo cmi1 = typeof(C1).GetMethod("M1");
        // Instance method with no arguments.
        MethodInfo cmi2 = typeof(C1).GetMethod("M2");
        // Static method with one argument of type C1.
        MethodInfo cmi3 = typeof(C1).GetMethod("M3");
        // Static method with two arguments of type C1.
        MethodInfo cmi4 = typeof(C1).GetMethod("M4");

        // Instance method with one argument of type C1.
        MethodInfo fmi1 = typeof(F).GetMethod("M1");
        // Static method with one argument of type C1.
        MethodInfo fmi3 = typeof(F).GetMethod("M3");
        // Static method with an argument of type F and an argument
        // of type C1.
        MethodInfo fmi4 = typeof(F).GetMethod("M4");

        Console.WriteLine("\nAn instance method on any type, with an argument of type C1.");
        // D can represent any instance method that exactly matches its
        // signature. Methods on C1 and F are shown here.
        //
        d = (D)Delegate.CreateDelegate(typeof(D), c1, cmi1);
        d(c2);
        d = (D)Delegate.CreateDelegate(typeof(D), f1, fmi1);
        d(c2);

        Console.WriteLine("\nAn instance method on C1 with no arguments.");
        // D can represent an instance method on C1 that has no arguments;
        // in this case, the argument of D represents the hidden first
        // argument of any instance method. The delegate acts like a
        // static method, and an instance of C1 must be passed each time
        // it is invoked.
        //
        d = (D)Delegate.CreateDelegate(typeof(D), null, cmi2);
        d(c1);

        Console.WriteLine("\nA static method on any type, with an argument of type C1.");
        // D can represent any static method with the same signature.
        // Methods on F and C1 are shown here.
        //
        d = (D)Delegate.CreateDelegate(typeof(D), null, cmi3);
        d(c1);
        d = (D)Delegate.CreateDelegate(typeof(D), null, fmi3);
        d(c1);

        Console.WriteLine("\nA static method on any type, with an argument of");
        Console.WriteLine("    that type and an argument of type C1.");
        // D can represent any static method with one argument of the
        // type the method belongs and a second argument of type C1.
        // In this case, the method is closed over the instance of
        // supplied for the its first argument, and acts like an instance
        // method. Methods on F and C1 are shown here.
        //
        d = (D)Delegate.CreateDelegate(typeof(D), c1, cmi4);
        d(c2);
        Delegate test =
            Delegate.CreateDelegate(typeof(D), f1, fmi4, false);

        // This final example specifies false for throwOnBindFailure
        // in the call to CreateDelegate, so the variable 'test'
        // contains Nothing if the method fails to bind (for
        // example, if fmi4 happened to represent a method of
        // some class other than F).
        //
        if (test != null)
        {
            d = (D)test;
            d(c2);
        }
    }
}

/* This code example produces the following output:

An instance method on any type, with an argument of type C1.
Instance method M1(C1 c) on C1:  this.id = 42, c.ID = 1491
Instance method M1(C1 c) on F:  c.ID = 1491

An instance method on C1 with no arguments.
Instance method M2() on C1:  this.id = 42

A static method on any type, with an argument of type C1.
Static method M3(C1 c) on C1:  c.ID = 42
Static method M3(C1 c) on F:  c.ID = 42

A static method on any type, with an argument of
    that type and an argument of type C1.
Static method M4(C1 c1, C1 c2) on C1:  c1.ID = 42, c2.ID = 1491
Static method M4(F f, C1 c) on F:  c.ID = 1491
*/
open System

// Declare two sample classes, C and F. Class C has an ID
// property so instances can be identified.
type C(id) =
    member _.ID = id 

    member _.M1(c: C) =
        printfn $"Instance method M1(C c) on C:  this.id = {id}, c.ID = {c.ID}"

    member _.M2() =
        printfn $"Instance method M2() on C:  this.id = {id}"

    static member M3(c: C) =
        printfn $"Static method M3(C c) on C:  c.ID = {c.ID}"

    static member M4(c1: C, c2: C) =
        printfn $"Static method M4(C c1, C c2) on C:  c1.ID = {c1.ID}, c2.ID = {c2.ID}"

// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
type D = delegate of C -> unit


type F() =
    member _.M1(c: C) =
        printfn $"Instance method M1(C c) on F:  c.ID = {c.ID}"

    member _.M3(c: C) =
        printfn $"Static method M3(C c) on F:  c.ID = {c.ID}"

    member _.M4(f: F, c: C) =
        printfn $"Static method M4(F f, C c) on F:  c.ID = {c.ID}"

[<EntryPoint>]
let main _ =
    let c1 = C 42
    let c2 = C 1491
    let f1 = F()

    // Instance method with one argument of type C.
    let cmi1 = typeof<C>.GetMethod "M1"
    // Instance method with no arguments.
    let cmi2 = typeof<C>.GetMethod "M2"
    // Static method with one argument of type C.
    let cmi3 = typeof<C>.GetMethod "M3"
    // Static method with two arguments of type C.
    let cmi4 = typeof<C>.GetMethod "M4"

    // Instance method with one argument of type C.
    let fmi1 = typeof<F>.GetMethod "M1"
    // Static method with one argument of type C.
    let fmi3 = typeof<F>.GetMethod "M3"
    // Static method with an argument of type F and an argument
    // of type C.
    let fmi4 = typeof<F>.GetMethod "M4"

    printfn "\nAn instance method on any type, with an argument of type C."
    // D can represent any instance method that exactly matches its
    // signature. Methods on C and F are shown here.
    let d = Delegate.CreateDelegate(typeof<D>, c1, cmi1) :?> D
    d.Invoke c2
    let d =  Delegate.CreateDelegate(typeof<D>, f1, fmi1) :?> D
    d.Invoke c2

    Console.WriteLine("\nAn instance method on C with no arguments.")
    // D can represent an instance method on C that has no arguments
    // in this case, the argument of D represents the hidden first
    // argument of any instance method. The delegate acts like a
    // static method, and an instance of C must be passed each time
    // it is invoked.
    let d = Delegate.CreateDelegate(typeof<D>, null, cmi2) :?> D
    d.Invoke c1

    printfn "\nA static method on any type, with an argument of type C."
    // D can represent any static method with the same signature.
    // Methods on F and C are shown here.
    let d = Delegate.CreateDelegate(typeof<D>, null, cmi3) :?> D
    d.Invoke c1
    let d = Delegate.CreateDelegate(typeof<D>, null, fmi3) :?> D
    d.Invoke c1

    printfn "\nA static method on any type, with an argument of"
    printfn "    that type and an argument of type C."
    // D can represent any static method with one argument of the
    // type the method belongs and a second argument of type C.
    // In this case, the method is closed over the instance of
    // supplied for the its first argument, and acts like an instance
    // method. Methods on F and C are shown here.
    let d = Delegate.CreateDelegate(typeof<D>, c1, cmi4) :?> D
    d.Invoke c2
    let test =
        Delegate.CreateDelegate(typeof<D>, f1, fmi4, false)

    // This final example specifies false for throwOnBindFailure
    // in the call to CreateDelegate, so the variable 'test'
    // contains Nothing if the method fails to bind (for
    // example, if fmi4 happened to represent a method of
    // some class other than F).
    match test with
    | :? D as d ->
        d.Invoke c2
    | _ -> ()
    0

// This code example produces the following output:
//     An instance method on any type, with an argument of type C.
//     Instance method M1(C c) on C:  this.id = 42, c.ID = 1491
//     Instance method M1(C c) on F:  c.ID = 1491
//    
//     An instance method on C with no arguments.
//     Instance method M2() on C:  this.id = 42
//    
//     A static method on any type, with an argument of type C.
//     Static method M3(C c) on C:  c.ID = 42
//     Static method M3(C c) on F:  c.ID = 42
//    
//     A static method on any type, with an argument of
//         that type and an argument of type C.
//     Static method M4(C c1, C c2) on C:  c1.ID = 42, c2.ID = 1491
//     Static method M4(F f, C c) on F:  c.ID = 1491
Imports System.Reflection
Imports System.Security.Permissions

' Declare a delegate type. The object of this code example
' is to show all the methods this delegate can bind to.
'
Public Delegate Sub D(ByVal c As C) 

' Declare two sample classes, C and F. Class C has an ID
' property so instances can be identified.
'
Public Class C

    Private _id As Integer

    Public ReadOnly Property ID() As Integer 
        Get
            Return _id
        End Get
    End Property

    Public Sub New(ByVal newId As Integer) 
        Me._id = newId
    End Sub
    
    Public Sub M1(ByVal c As C) 
        Console.WriteLine("Instance method M1(c As C) on C:  this.id = {0}, c.ID = {1}", _
            Me.id, c.ID)
    End Sub
    
    Public Sub M2() 
        Console.WriteLine("Instance method M2() on C:  this.id = {0}", Me.id)
    End Sub
    
    Public Shared Sub M3(ByVal c As C) 
        Console.WriteLine("Shared method M3(c As C) on C:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M4(ByVal c1 As C, ByVal c2 As C) 
        Console.WriteLine("Shared method M4(c1 As C, c2 As C) on C:  c1.ID = {0}, c2.ID = {1}", _
            c1.ID, c2.ID)
    End Sub
End Class


Public Class F
    
    Public Sub M1(ByVal c As C) 
        Console.WriteLine("Instance method M1(c As C) on F:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M3(ByVal c As C) 
        Console.WriteLine("Shared method M3(c As C) on F:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M4(ByVal f As F, ByVal c As C) 
        Console.WriteLine("Shared method M4(f As F, c As C) on F:  c.ID = {0}", c.ID)
    End Sub
End Class

Public Class Example5

    Public Shared Sub Main()

        Dim c1 As New C(42)
        Dim c2 As New C(1491)
        Dim f1 As New F()

        Dim d As D

        ' Instance method with one argument of type C.
        Dim cmi1 As MethodInfo = GetType(C).GetMethod("M1")
        ' Instance method with no arguments.
        Dim cmi2 As MethodInfo = GetType(C).GetMethod("M2")
        ' Shared method with one argument of type C.
        Dim cmi3 As MethodInfo = GetType(C).GetMethod("M3")
        ' Shared method with two arguments of type C.
        Dim cmi4 As MethodInfo = GetType(C).GetMethod("M4")

        ' Instance method with one argument of type C.
        Dim fmi1 As MethodInfo = GetType(F).GetMethod("M1")
        ' Shared method with one argument of type C.
        Dim fmi3 As MethodInfo = GetType(F).GetMethod("M3")
        ' Shared method with an argument of type F and an 
        ' argument of type C.
        Dim fmi4 As MethodInfo = GetType(F).GetMethod("M4")

        Console.WriteLine(vbLf & "An instance method on any type, with an argument of type C.")
        ' D can represent any instance method that exactly matches its
        ' signature. Methods on C and F are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi1), D)
        d(c2)
        d = CType([Delegate].CreateDelegate(GetType(D), f1, fmi1), D)
        d(c2)

        Console.WriteLine(vbLf & "An instance method on C with no arguments.")
        ' D can represent an instance method on C that has no arguments;
        ' in this case, the argument of D represents the hidden first
        ' argument of any instance method. The delegate acts like a 
        ' Shared method, and an instance of C must be passed each time
        ' it is invoked.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi2), D)
        d(c1)

        Console.WriteLine(vbLf & "A Shared method on any type, with an argument of type C.")
        ' D can represent any Shared method with the same signature.
        ' Methods on F and C are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi3), D)
        d(c1)
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, fmi3), D)
        d(c1)

        Console.WriteLine(vbLf & "A Shared method on any type, with an argument of")
        Console.WriteLine("    that type and an argument of type C.")
        ' D can represent any Shared method with one argument of the
        ' type the method belongs and a second argument of type C.
        ' In this case, the method is closed over the instance of
        ' supplied for the its first argument, and acts like an instance
        ' method. Methods on F and C are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi4), D)
        d(c2)
        Dim test As [Delegate] =
            [Delegate].CreateDelegate(GetType(D), f1, fmi4, False)

        ' This final example specifies False for throwOnBindFailure 
        ' in the call to CreateDelegate, so the variable 'test'
        ' contains Nothing if the method fails to bind (for 
        ' example, if fmi4 happened to represent a method of  
        ' some class other than F).
        '
        If test IsNot Nothing Then
            d = CType(test, D)
            d(c2)
        End If

    End Sub
End Class

' This code example produces the following output:
'
'An instance method on any type, with an argument of type C.
'Instance method M1(c As C) on C:  this.id = 42, c.ID = 1491
'Instance method M1(c As C) on F:  c.ID = 1491
'
'An instance method on C with no arguments.
'Instance method M2() on C:  this.id = 42
'
'A Shared method on any type, with an argument of type C.
'Shared method M3(c As C) on C:  c.ID = 42
'Shared method M3(c As C) on F:  c.ID = 42
'
'A Shared method on any type, with an argument of
'    that type and an argument of type C.
'Shared method M4(c1 As C, c2 As C) on C:  c1.ID = 42, c2.ID = 1491
'Shared method M4(f As F, c As C) on F:  c.ID = 1491
'

Uyumlu parametre türleri ve dönüş türü

Bu yöntem aşırı yüklemesi kullanılarak oluşturulan bir temsilcinin parametre türleri ve dönüş türü, temsilcinin temsil ettiği yöntemin parametre türleri ve dönüş türüyle uyumlu olmalıdır; türlerin tam olarak eşleşmesi gerekmez.

Temsilci parametresinin türü yöntem parametresinin türünden daha kısıtlayıcıysa, temsilcinin parametresi bir yöntemin ilgili parametresiyle uyumludur, çünkü bu, temsilciye geçirilen bir bağımsız değişkenin yönteme güvenli bir şekilde geçirilebileceğini garanti eder.

Benzer şekilde, bir temsilcinin dönüş türü, yöntemin dönüş türü temsilcinin dönüş türünden daha kısıtlayıcı olduğunda yöntemle uyumludur. Bu, yöntemin dönüş değerinin temsilcinin dönüş türüne güvenli bir şekilde dönüştürülebileceğini garanti eder.

Örneğin, Hashtable türünde bir parametreye ve Object dönüş türüne sahip bir temsilci, Object türünde bir parametreye ve Hashtabletüründe bir dönüş değerine sahip bir yöntemi temsil edebilir.

Temsilcinin gösterebileceği yöntemleri belirleme

CreateDelegate(Type, Object, MethodInfo) aşırı yüklemesi tarafından sağlanan esnekliği düşünmenin bir diğer kullanışlı yolu, belirli bir temsilcinin dört farklı yöntem imzası ve yöntem türü birleşimini (statik ve örnek) temsil edebilmesidir. Dtüründe bir bağımsız değişken içeren bir temsilci türü C düşünün. Aşağıda, D her durumda eşleşmesi gerektiğinden dönüş türünü yoksayarak temsil edebileceği yöntemler açıklanmaktadır.

  • D, örnek yönteminin ait olduğu türe bakılmaksızın Ctüründe tam olarak bir bağımsız değişkeni olan herhangi bir örnek yöntemini temsil edebilir. CreateDelegate çağrıldığında, firstArgumentmethod ait olduğu türün bir örneğidir ve sonuçta elde edilen temsilcinin bu örnek üzerinde kapatılacağı söylenir. (Açıkça, D null referansıysa, firstArgument da bir null referans üzerinden kapatılabilir.)

  • D argümansız bir C örnek metodunu temsil edebilir. CreateDelegate çağrıldığında, firstArgument boş bir başvurudur. Ortaya çıkan delege, açık bir örnek yöntemini temsil eder ve her çağrıldığında bir C örneği sağlanmalıdır.

  • D, Ctüründe bir parametre alan statik bir yöntemi temsil edebilir ve bu yöntem herhangi bir türe ait olabilir. CreateDelegate çağrıldığında, firstArgument boş bir başvurudur. Sonuçta elde edilen temsilci açık bir statik yöntemi temsil eder ve her çağrıldığında bir C örneği sağlanmalıdır.

  • D, F türüne ait olan ve F türünde ve Ctüründe iki bağımsız değişkeni olan statik bir yöntemi temsil edebilir. CreateDelegate çağrıldığında, firstArgument bir Förneğidir. Sonuçta elde edilen temsilci, Förneği üzerinden kapatılan statik bir yöntemi temsil eder. F ve C aynı türde olması durumunda statik yöntemin bu türde iki bağımsız değişkeni olduğunu unutmayın. (Bu durumda, D null başvuruysa firstArgument null başvuru üzerinden kapatılır.)

Açıklamalar

Bu yöntem aşırı yüklemesini çağırmak, yöntem aşırı yüklemesini çağırmaya CreateDelegate(Type, Object, MethodInfo, Boolean) ve için truebelirtmeye throwOnBindFailure eşdeğerdir. Bu iki aşırı yükleme, temsilci oluşturmanın en esnek yolunu sağlar. Bunları kullanarak statik veya örnek yöntemleri için temsilciler oluşturabilir ve isteğe bağlı olarak ilk bağımsız değişkeni belirtebilirsiniz.

Note

İlk bağımsız değişken sağlamazsanız, daha iyi performans için yöntem aşırı yüklemesini CreateDelegate(Type, MethodInfo) kullanın.

CreateDelegate yöntemleri, belirtilen türde bir temsilci oluşturur.

CreateDelegate(Type, MethodInfo) yöntemi

Bu yöntem aşırı yüklemesi, CreateDelegate(Type, MethodInfo, Boolean) yöntemi aşırı yüklemesini çağırmaya ve trueiçin throwOnBindFailure belirtmeye eşdeğerdir.

Ayrıca bkz.

Şunlara uygulanır

CreateDelegate(Type, MethodInfo)

Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs

Belirtilen yöntemi temsil etmek için belirtilen türde bir temsilci oluşturur.

public:
 static Delegate ^ CreateDelegate(Type ^ type, System::Reflection::MethodInfo ^ method);
public static Delegate CreateDelegate(Type type, System.Reflection.MethodInfo method);
static member CreateDelegate : Type * System.Reflection.MethodInfo -> Delegate
Public Shared Function CreateDelegate (type As Type, method As MethodInfo) As Delegate

Parametreler

type
Type

Type Oluşturulacak temsilci.

method
MethodInfo

Temsilcinin MethodInfo temsil etmek üzere olduğu statik veya örnek yöntemini açıklayan.

Döndürülenler

Belirtilen yöntemi temsil etmek için belirtilen türün temsilcisi.

Özel durumlar

type, null'e eşittir.

-veya-

method, null'e eşittir.

type devralmıyor MulticastDelegate.

-veya-

type bir RuntimeTypedeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

-veya-

method bağlanamıyor.

-veya-

method bir RuntimeMethodInfodeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

Invoke yöntemi type bulunamadı.

Çağıranın erişimi methodiçin gerekli izinlere sahip değil.

Örnekler

Bu bölüm iki kod örneği içerir. İlk örnekte, bu yöntem aşırı yüklemesiyle oluşturulabilecek iki tür temsilci gösterilmektedir: örnek yöntemi üzerinden açma ve statik bir yöntem üzerinden açma.

İkinci kod örneği uyumlu parametre türlerini ve dönüş türlerini gösterir.

Örnek 1

Aşağıdaki kod örneğinde, CreateDelegate yönteminin bu aşırı yüklemesi kullanılarak temsilci oluşturmanın iki yolu gösterilmektedir.

Note

CreateDelegate yönteminin bir MethodInfo belirten ancak ilk bağımsız değişkeni belirtmeyen iki aşırı yüklemesi vardır; işlevleri aynıdır, ancak biri bağlama hatasının atılıp atılmayacağını belirtmenize olanak tanır ve diğeri her zaman atar. Bu kod örneği her iki aşırı yüklemeyi de kullanır.

Örnek, bir sınıf C, statik bir metot M2 ve bir örnek metot M1ile iki temsilci türü bildirir: D1, bir C örneği ve bir dize alır; D2 ise bir dize alır.

Example adlı ikinci sınıf, temsilcileri oluşturan kodu içerir.

  • D1örnek yöntemi için açık örnek yöntemini temsil eden M1türünde bir temsilci oluşturulur. Temsilci çağrıldığında bir örnek geçirilmelidir.
  • D2statik yöntemi için açık statik yöntemi temsil eden M2türünde bir temsilci oluşturulur.
using System;
using System.Reflection;

// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
//
public delegate void D1(C c, string s);
public delegate void D2(string s);
public delegate void D3();

// A sample class with an instance method and a static method.
//
public class C
{
    private int id;
    public C(int id) { this.id = id; }

    public void M1(string s) =>
        Console.WriteLine($"Instance method M1 on C:  id = {this.id}, s = {s}");

    public static void M2(string s)
    {
        Console.WriteLine($"Static method M2 on C:  s = {s}");
    }
}

public class Example2
{
    public static void Main()
    {
        C c1 = new C(42);

        // Get a MethodInfo for each method.
        //
        MethodInfo mi1 = typeof(C).GetMethod("M1",
            BindingFlags.Public | BindingFlags.Instance);
        MethodInfo mi2 = typeof(C).GetMethod("M2",
            BindingFlags.Public | BindingFlags.Static);

        D1 d1;
        D2 d2;
        D3 d3;

        Console.WriteLine("\nAn instance method closed over C.");
        // In this case, the delegate and the
        // method must have the same list of argument types; use
        // delegate type D2 with instance method M1.
        //
        Delegate test =
            Delegate.CreateDelegate(typeof(D2), c1, mi1, false);

        // Because false was specified for throwOnBindFailure
        // in the call to CreateDelegate, the variable 'test'
        // contains null if the method fails to bind (for
        // example, if mi1 happened to represent a method of
        // some class other than C).
        //
        if (test != null)
        {
            d2 = (D2)test;

            // The same instance of C is used every time the
            // delegate is invoked.
            d2("Hello, World!");
            d2("Hi, Mom!");
        }

        Console.WriteLine("\nAn open instance method.");
        // In this case, the delegate has one more
        // argument than the instance method; this argument comes
        // at the beginning, and represents the hidden instance
        // argument of the instance method. Use delegate type D1
        // with instance method M1.
        //
        d1 = (D1)Delegate.CreateDelegate(typeof(D1), null, mi1);

        // An instance of C must be passed in each time the
        // delegate is invoked.
        //
        d1(c1, "Hello, World!");
        d1(new C(5280), "Hi, Mom!");

        Console.WriteLine("\nAn open static method.");
        // In this case, the delegate and the method must
        // have the same list of argument types; use delegate type
        // D2 with static method M2.
        //
        d2 = (D2)Delegate.CreateDelegate(typeof(D2), null, mi2);

        // No instances of C are involved, because this is a static
        // method.
        //
        d2("Hello, World!");
        d2("Hi, Mom!");

        Console.WriteLine("\nA static method closed over the first argument (String).");
        // The delegate must omit the first argument of the method.
        // A string is passed as the firstArgument parameter, and
        // the delegate is bound to this string. Use delegate type
        // D3 with static method M2.
        //
        d3 = (D3)Delegate.CreateDelegate(typeof(D3),
            "Hello, World!", mi2);

        // Each time the delegate is invoked, the same string is
        // used.
        d3();
    }
}

/* This code example produces the following output:

An instance method closed over C.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 42, s = Hi, Mom!

An open instance method.
Instance method M1 on C:  id = 42, s = Hello, World!
Instance method M1 on C:  id = 5280, s = Hi, Mom!

An open static method.
Static method M2 on C:  s = Hello, World!
Static method M2 on C:  s = Hi, Mom!

A static method closed over the first argument (String).
Static method M2 on C:  s = Hello, World!
 */
open System
open System.Reflection

// A sample class with an instance method and a static method.
type C(id) =
    member _.M1(s) =
        printfn $"Instance method M1 on C:  id = %i{id}, s = %s{s}"

    static member M2(s) =
        printfn $"Static method M2 on C:  s = %s{s}"
    
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
type D1 = delegate of C * string -> unit
type D2 = delegate of string -> unit
type D3 = delegate of unit -> unit

let c1 = C 42

// Get a MethodInfo for each method.
//
let mi1 = typeof<C>.GetMethod("M1", BindingFlags.Public ||| BindingFlags.Instance)
let mi2 = typeof<C>.GetMethod("M2", BindingFlags.Public ||| BindingFlags.Static)

printfn "\nAn instance method closed over C."

// In this case, the delegate and the
// method must have the same list of argument types use
// delegate type D2 with instance method M1.
let test = Delegate.CreateDelegate(typeof<D2>, c1, mi1, false)

// Because false was specified for throwOnBindFailure
// in the call to CreateDelegate, the variable 'test'
// contains null if the method fails to bind (for
// example, if mi1 happened to represent a method of
// some class other than C).
if test <> null then
    let d2 = test :?> D2

    // The same instance of C is used every time the
    // delegate is invoked.
    d2.Invoke "Hello, World!"
    d2.Invoke "Hi, Mom!"

printfn "\nAn open instance method."

// In this case, the delegate has one more
// argument than the instance method this argument comes
// at the beginning, and represents the hidden instance
// argument of the instance method. Use delegate type D1
// with instance method M1.
let d1 = Delegate.CreateDelegate(typeof<D1>, null, mi1) :?> D1

// An instance of C must be passed in each time the
// delegate is invoked.
d1.Invoke(c1, "Hello, World!")
d1.Invoke(C 5280, "Hi, Mom!")

printfn "\nAn open static method."
// In this case, the delegate and the method must
// have the same list of argument types use delegate type
// D2 with static method M2.
let d2 = Delegate.CreateDelegate(typeof<D2>, null, mi2) :?> D2

// No instances of C are involved, because this is a static
// method.
d2.Invoke "Hello, World!"
d2.Invoke "Hi, Mom!"

printfn "\nA static method closed over the first argument (String)."
// The delegate must omit the first argument of the method.
// A string is passed as the firstArgument parameter, and
// the delegate is bound to this string. Use delegate type
// D3 with static method M2.
let d3 = Delegate.CreateDelegate(typeof<D3>, "Hello, World!", mi2) :?> D3

// Each time the delegate is invoked, the same string is used.
d3.Invoke()

// This code example produces the following output:
//     An instance method closed over C.
//     Instance method M1 on C:  id = 42, s = Hello, World!
//     Instance method M1 on C:  id = 42, s = Hi, Mom!
//     
//     An open instance method.
//     Instance method M1 on C:  id = 42, s = Hello, World!
//     Instance method M1 on C:  id = 5280, s = Hi, Mom!
//     
//     An open static method.
//     Static method M2 on C:  s = Hello, World!
//     Static method M2 on C:  s = Hi, Mom!
//     
//     A static method closed over the first argument (String).
//     Static method M2 on C:  s = Hello, World!
Imports System.Reflection
Imports System.Security.Permissions

' Declare three delegate types for demonstrating the combinations
' of Shared versus instance methods and open versus closed
' delegates.
'
Public Delegate Sub D1(ByVal c As C2, ByVal s As String)
Public Delegate Sub D2(ByVal s As String)
Public Delegate Sub D3()

' A sample class with an instance method and a Shared method.
'
Public Class C2
    Private id As Integer
    Public Sub New(ByVal id As Integer)
        Me.id = id
    End Sub

    Public Sub M1(ByVal s As String)
        Console.WriteLine("Instance method M1 on C2:  id = {0}, s = {1}",
            Me.id, s)
    End Sub

    Public Shared Sub M2(ByVal s As String)
        Console.WriteLine("Shared method M2 on C2:  s = {0}", s)
    End Sub
End Class

Public Class Example2

    Public Shared Sub Main()

        Dim c1 As New C2(42)

        ' Get a MethodInfo for each method.
        '
        Dim mi1 As MethodInfo = GetType(C2).GetMethod("M1",
            BindingFlags.Public Or BindingFlags.Instance)
        Dim mi2 As MethodInfo = GetType(C2).GetMethod("M2",
            BindingFlags.Public Or BindingFlags.Static)

        Dim d1 As D1
        Dim d2 As D2
        Dim d3 As D3


        Console.WriteLine(vbLf & "An instance method closed over C2.")
        ' In this case, the delegate and the
        ' method must have the same list of argument types; use
        ' delegate type D2 with instance method M1.
        '
        Dim test As [Delegate] =
            [Delegate].CreateDelegate(GetType(D2), c1, mi1, False)

        ' Because False was specified for throwOnBindFailure 
        ' in the call to CreateDelegate, the variable 'test'
        ' contains Nothing if the method fails to bind (for 
        ' example, if mi1 happened to represent a method of 
        ' some class other than C2).
        '
        If test IsNot Nothing Then
            d2 = CType(test, D2)

            ' The same instance of C2 is used every time the
            ' delegate is invoked.
            d2("Hello, World!")
            d2("Hi, Mom!")
        End If


        Console.WriteLine(vbLf & "An open instance method.")
        ' In this case, the delegate has one more 
        ' argument than the instance method; this argument comes
        ' at the beginning, and represents the hidden instance
        ' argument of the instance method. Use delegate type D1
        ' with instance method M1.
        '
        d1 = CType([Delegate].CreateDelegate(GetType(D1), Nothing, mi1), D1)

        ' An instance of C2 must be passed in each time the 
        ' delegate is invoked.
        '
        d1(c1, "Hello, World!")
        d1(New C2(5280), "Hi, Mom!")


        Console.WriteLine(vbLf & "An open Shared method.")
        ' In this case, the delegate and the method must 
        ' have the same list of argument types; use delegate type
        ' D2 with Shared method M2.
        '
        d2 = CType([Delegate].CreateDelegate(GetType(D2), Nothing, mi2), D2)

        ' No instances of C2 are involved, because this is a Shared
        ' method. 
        '
        d2("Hello, World!")
        d2("Hi, Mom!")


        Console.WriteLine(vbLf & "A Shared method closed over the first argument (String).")
        ' The delegate must omit the first argument of the method.
        ' A string is passed as the firstArgument parameter, and 
        ' the delegate is bound to this string. Use delegate type 
        ' D3 with Shared method M2. 
        '
        d3 = CType([Delegate].CreateDelegate(GetType(D3), "Hello, World!", mi2), D3)

        ' Each time the delegate is invoked, the same string is
        ' used.
        d3()

    End Sub
End Class

' This code example produces the following output:
'
'An instance method closed over C2.
'Instance method M1 on C2:  id = 42, s = Hello, World!
'Instance method M1 on C2:  id = 42, s = Hi, Mom!
'
'An open instance method.
'Instance method M1 on C2:  id = 42, s = Hello, World!
'Instance method M1 on C2:  id = 5280, s = Hi, Mom!
'
'An open Shared method.
'Shared method M2 on C2:  s = Hello, World!
'Shared method M2 on C2:  s = Hi, Mom!
'
'A Shared method closed over the first argument (String).
'Shared method M2 on C2:  s = Hello, World!
'

Örnek 2

Aşağıdaki kod örneği, parametre türlerinin ve dönüş türlerinin uyumluluğunu gösterir.

Kod örneği, Base adlı bir temel sınıfı ve Derivedtüretilen Base adlı bir sınıfı tanımlar. Türetilen sınıfın static türünde bir parametresi ve Shareddönüş türüyle MyMethod adlı Base ( Visual Basic'teDerived) yöntemi vardır. Kod örneği, Example türünde bir parametresi ve Deriveddönüş türüne sahip Base adlı bir temsilci de tanımlar.

Kod örneği, Example adlı temsilcinin MyMethodyöntemini temsil etmek için kullanılabileceğini gösterir. Yöntemi temsilciye bağlanabilir çünkü:

  • Temsilcinin parametre türü (Derived), MyMethod'in parametre türünden daha sınırlayıcıdır (Base), bu yüzden temsilcinin bağımsız değişkeninin MyMethod'e aktarılması her zaman güvenlidir.
  • MyMethod (Derived) dönüş türü, temsilcinin parametre türünden daha kısıtlayıcıdır (Base), bu nedenle yöntemin dönüş türünü temsilcinin dönüş türüne atamak her zaman güvenlidir.

Kod örneği çıkış üretmez.

using System;
using System.Reflection;

// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
//
public class Base { }

public class Derived : Base
{
    // Define a static method to use in the demonstration. The method
    // takes an instance of Base and returns an instance of Derived.
    // For the purposes of the demonstration, it is not necessary for
    // the method to do anything useful.
    //
    public static Derived MyMethod(Base arg)
    {
        Base dummy = arg;
        return new Derived();
    }
}

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base Example5(Derived arg);

class Test
{
    public static void Main()
    {
        // The binding flags needed to retrieve MyMethod.
        BindingFlags flags = BindingFlags.Public | BindingFlags.Static;

        // Get a MethodInfo that represents MyMethod.
        MethodInfo minfo = typeof(Derived).GetMethod("MyMethod", flags);

        // Demonstrate contravariance of parameter types and covariance
        // of return types by using the delegate Example5 to represent
        // MyMethod. The delegate binds to the method because the
        // parameter of the delegate is more restrictive than the
        // parameter of the method (that is, the delegate accepts an
        // instance of Derived, which can always be safely passed to
        // a parameter of type Base), and the return type of MyMethod
        // is more restrictive than the return type of Example5 (that
        // is, the method returns an instance of Derived, which can
        // always be safely cast to type Base).
        //
        Example5 ex =
            (Example5)Delegate.CreateDelegate(typeof(Example5), minfo);

        // Execute MyMethod using the delegate Example5.
        //
        Base b = ex(new Derived());
    }
}
open System
open System.Reflection

// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
type Base() = class end

type Derived() =
    inherit Base()

    // Define a static method to use in the demonstration. The method
    // takes an instance of Base and returns an instance of Derived.
    // For the purposes of the demonstration, it is not necessary for
    // the method to do anything useful.
    static member MyMethod(arg: Base) =
        Derived()

// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
type Example = delegate of Derived -> Base

// The binding flags needed to retrieve MyMethod.
let flags = BindingFlags.Public ||| BindingFlags.Static

// Get a MethodInfo that represents MyMethod.
let minfo = typeof<Derived>.GetMethod("MyMethod", flags)

// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
let ex = Delegate.CreateDelegate(typeof<Example>, minfo) :?> Example

// Execute MyMethod using the delegate Example.
let b = Derived() |> ex.Invoke
Imports System.Reflection

' Define two classes to use in the demonstration, a base class and 
' a class that derives from it.
'
Public Class Base
End Class

Public Class Derived
    Inherits Base

    ' Define a Shared method to use in the demonstration. The method 
    ' takes an instance of Base and returns an instance of Derived.  
    ' For the purposes of the demonstration, it is not necessary for 
    ' the method to do anything useful. 
    '
    Public Shared Function MyMethod(ByVal arg As Base) As Derived
        Dim dummy As Base = arg
        Return New Derived()
    End Function

End Class

' Define a delegate that takes an instance of Derived and returns an
' instance of Base.
'
Public Delegate Function Example(ByVal arg As Derived) As Base

Module Test

    Sub Main()

        ' The binding flags needed to retrieve MyMethod.
        Dim flags As BindingFlags = _
            BindingFlags.Public Or BindingFlags.Static

        ' Get a MethodInfo that represents MyMethod.
        Dim minfo As MethodInfo = _
            GetType(Derived).GetMethod("MyMethod", flags)

        ' Demonstrate contravariance of parameter types and covariance
        ' of return types by using the delegate Example to represent
        ' MyMethod. The delegate binds to the method because the
        ' parameter of the delegate is more restrictive than the 
        ' parameter of the method (that is, the delegate accepts an
        ' instance of Derived, which can always be safely passed to
        ' a parameter of type Base), and the return type of MyMethod
        ' is more restrictive than the return type of Example (that
        ' is, the method returns an instance of Derived, which can
        ' always be safely cast to type Base). 
        '
        Dim ex As Example = CType( _
            [Delegate].CreateDelegate(GetType(Example), minfo), _
            Example _
        )

        ' Execute MyMethod using the delegate Example.
        '        
        Dim b As Base = ex(New Derived())
    End Sub
End Module

CreateDelegate(Type, Object, MethodInfo) ve CreateDelegate(Type, Object, MethodInfo, Boolean) yöntemleri

Bu iki aşırı yüklemenin işlevselliği aynıdır, ancak biri bağlama hatasında atılıp atılmayacağını belirtmenize olanak tanır ve diğeri her zaman atar.

Temsilci türü ve yöntemi uyumlu dönüş türlerine sahip olmalıdır. Yani, method dönüş türü typedönüş türüne atanabilir olmalıdır.

firstArgument, bu aşırı yüklemelerin ikinci parametresi, temsilcinin temsil ettiği yöntemin ilk bağımsız değişkenidir. firstArgument sağlanırsa, temsilci her çağrıldığında firstArgumentfirstArgument'e iletilir; 'nin temsilciye bağlı olduğu ve temsilcinin ilk bağımsız değişkeni üzerinde işlevsel olarak kapandığı söylenir. method static ise (Visual Basic'teShared), temsilci çağrılırken sağlanan bağımsız değişken listesi ilk parametre dışındaki tüm parametreleri içerir; method bir örnek yöntemiyse, gizli örnek parametresine (C# dilinde firstArgument veya Visual Basic'teki this tarafından temsil edilen) Me geçirilir.

firstArgument sağlanırsa, method ilk parametresi bir başvuru türü olmalı ve firstArgument bu türle uyumlu olmalıdır.

Important

method static (Visual Basic'teShared) ve ilk parametresi Object veya ValueTypetüründeyse, firstArgument bir değer türü olabilir. Bu durumda firstArgument otomatik olarak kutulanır. C# veya Visual Basic işlev çağrısında olduğu gibi diğer bağımsız değişkenler için otomatik kutulama gerçekleşmez.

firstArgument null referans ve method bir örnek metot ise, sonuç delege tipi type ve methodimzalarına bağlıdır.

  • type imzası açıkça methodgizli ilk parametresini içeriyorsa, temsilcinin açık bir örnek yöntemini temsil ettiğini söylenir. Temsilci çağrıldığında, bağımsız değişken listesindeki ilk bağımsız değişken methodgizli örnek parametresine geçirilir.
  • method ve type imzaları eşleşiyorsa (yani, tüm parametre türleri uyumludur), temsilcinin null referansı üzerinde kapatıldığı söylenir. Temsilciyi çağırmak, null örnekte bir örnek yöntemini çağırmak gibidir ve bu özellikle yararlı bir işlem değildir.

firstArgument null başvuruysa ve method statikse, sonuç temsilci türü type ve methodimzalarına bağlıdır:

  • method ve type imzası eşleşiyorsa (diğer bir ifadeyle tüm parametre türleri uyumludur), temsilcinin açık statik bir yöntemi temsil olduğu söylenir. Bu, statik yöntemler için en yaygın durumdur. Bu durumda, CreateDelegate(Type, MethodInfo) metot aşırı yüklemesini kullanarak biraz daha iyi bir performans elde edebilirsiniz.
  • type imzası, method'in ikinci parametresiyle başlıyorsa ve geri kalan parametre türleri uyumluysa, temsilcinin null bir referans üzerinde kapatıldığı söylenir. Temsilci çağrıldığında, method'ın ilk parametresine boş bir referans geçirilir.

Example

Aşağıdaki kod örneği, tek bir temsilci türünün gösterebileceği tüm yöntemleri gösterir: örnek yöntemi üzerinden kapatılır, örnek yöntemi üzerinden açılır, statik yöntem üzerinden açılır ve statik yöntem üzerinden kapatılır.

Kod örneği, C ve Folmak üzere iki sınıfı ve Dtüründe bir bağımsız değişkeni olan bir temsilci türü C tanımlar. Sınıfların, M1, M3ve M4ile eşleşen statik ve örnek yöntemleri vardır ve sınıf C'ün, bağımsız değişkeni olmayan bir örnek yöntemi M2 sahiptir.

Example adlı üçüncü sınıf, temsilcileri oluşturan kodu içerir.

  • Temsilciler, M1 örnek yöntemi ile C ve Ftürleri için oluşturulur; her biri ilgili türün bir örneğine göre kapatılır. M1 yönteminin C türü, bağlı örneğin ve bağımsız değişkenin ID özelliklerini görüntüler.
  • M2türünde yöntem C için bir temsilci oluşturulur. Bu, temsilci bağımsız değişkeninin örnek yöntemindeki gizli ilk bağımsız değişkeni temsil ettiği açık örnek temsilcisidir. Yöntemin başka parametresi yok. Statik bir yöntemmiş gibi çağrılır.
  • Temsilciler, M3 statik yöntemi için C türü ve Ftürü olarak oluşturulur; bunlar açık statik temsilcilerdir.
  • Son olarak, M4 türüne ve Ctürüne ait olan statik yöntem F için temsilciler oluşturulur; her yöntemin bildirim türü ilk bağımsız değişken olarak görev yapar ve türün bir örneği sağlandığı için, temsilciler ilk bağımsız değişkenleri üzerine kapatılır. M4 yönteminin C türü, bağlı örneğin ve bağımsız değişkenin ID özelliklerini görüntüler.
using System;
using System.Reflection;

// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
//
public delegate void D(C1 c);

// Declare two sample classes, C1 and F. Class C1 has an ID
// property so instances can be identified.
//
public class C1
{
    private int id;
    public int ID => id;
    public C1(int id) => this.id = id;

    public void M1(C1 c)
    {
        Console.WriteLine("Instance method M1(C1 c) on C1:  this.id = {0}, c.ID = {1}",
            this.id, c.ID);
    }

    public void M2()
    {
        Console.WriteLine($"Instance method M2() on C1:  this.id = {this.id}");
    }

    public static void M3(C1 c)
    {
        Console.WriteLine($"Static method M3(C1 c) on C1:  c.ID = {c.ID}");
    }

    public static void M4(C1 c1, C1 c2)
    {
        Console.WriteLine("Static method M4(C1 c1, C1 c2) on C1:  c1.ID = {0}, c2.ID = {1}",
            c1.ID, c2.ID);
    }
}

public class F
{
    public void M1(C1 c)
    {
        Console.WriteLine($"Instance method M1(C1 c) on F:  c.ID = {c.ID}");
    }

    public static void M3(C1 c)
    {
        Console.WriteLine($"Static method M3(C1 c) on F:  c.ID = {c.ID}");
    }

    public static void M4(F f, C1 c)
    {
        Console.WriteLine($"Static method M4(F f, C1 c) on F:  c.ID = {c.ID}");
    }
}

public class Example
{
    public static void Main()
    {
        C1 c1 = new (42);
        C1 c2 = new (1491);
        F f1 = new ();

        D d;

        // Instance method with one argument of type C1.
        MethodInfo cmi1 = typeof(C1).GetMethod("M1");
        // Instance method with no arguments.
        MethodInfo cmi2 = typeof(C1).GetMethod("M2");
        // Static method with one argument of type C1.
        MethodInfo cmi3 = typeof(C1).GetMethod("M3");
        // Static method with two arguments of type C1.
        MethodInfo cmi4 = typeof(C1).GetMethod("M4");

        // Instance method with one argument of type C1.
        MethodInfo fmi1 = typeof(F).GetMethod("M1");
        // Static method with one argument of type C1.
        MethodInfo fmi3 = typeof(F).GetMethod("M3");
        // Static method with an argument of type F and an argument
        // of type C1.
        MethodInfo fmi4 = typeof(F).GetMethod("M4");

        Console.WriteLine("\nAn instance method on any type, with an argument of type C1.");
        // D can represent any instance method that exactly matches its
        // signature. Methods on C1 and F are shown here.
        //
        d = (D)Delegate.CreateDelegate(typeof(D), c1, cmi1);
        d(c2);
        d = (D)Delegate.CreateDelegate(typeof(D), f1, fmi1);
        d(c2);

        Console.WriteLine("\nAn instance method on C1 with no arguments.");
        // D can represent an instance method on C1 that has no arguments;
        // in this case, the argument of D represents the hidden first
        // argument of any instance method. The delegate acts like a
        // static method, and an instance of C1 must be passed each time
        // it is invoked.
        //
        d = (D)Delegate.CreateDelegate(typeof(D), null, cmi2);
        d(c1);

        Console.WriteLine("\nA static method on any type, with an argument of type C1.");
        // D can represent any static method with the same signature.
        // Methods on F and C1 are shown here.
        //
        d = (D)Delegate.CreateDelegate(typeof(D), null, cmi3);
        d(c1);
        d = (D)Delegate.CreateDelegate(typeof(D), null, fmi3);
        d(c1);

        Console.WriteLine("\nA static method on any type, with an argument of");
        Console.WriteLine("    that type and an argument of type C1.");
        // D can represent any static method with one argument of the
        // type the method belongs and a second argument of type C1.
        // In this case, the method is closed over the instance of
        // supplied for the its first argument, and acts like an instance
        // method. Methods on F and C1 are shown here.
        //
        d = (D)Delegate.CreateDelegate(typeof(D), c1, cmi4);
        d(c2);
        Delegate test =
            Delegate.CreateDelegate(typeof(D), f1, fmi4, false);

        // This final example specifies false for throwOnBindFailure
        // in the call to CreateDelegate, so the variable 'test'
        // contains Nothing if the method fails to bind (for
        // example, if fmi4 happened to represent a method of
        // some class other than F).
        //
        if (test != null)
        {
            d = (D)test;
            d(c2);
        }
    }
}

/* This code example produces the following output:

An instance method on any type, with an argument of type C1.
Instance method M1(C1 c) on C1:  this.id = 42, c.ID = 1491
Instance method M1(C1 c) on F:  c.ID = 1491

An instance method on C1 with no arguments.
Instance method M2() on C1:  this.id = 42

A static method on any type, with an argument of type C1.
Static method M3(C1 c) on C1:  c.ID = 42
Static method M3(C1 c) on F:  c.ID = 42

A static method on any type, with an argument of
    that type and an argument of type C1.
Static method M4(C1 c1, C1 c2) on C1:  c1.ID = 42, c2.ID = 1491
Static method M4(F f, C1 c) on F:  c.ID = 1491
*/
open System

// Declare two sample classes, C and F. Class C has an ID
// property so instances can be identified.
type C(id) =
    member _.ID = id 

    member _.M1(c: C) =
        printfn $"Instance method M1(C c) on C:  this.id = {id}, c.ID = {c.ID}"

    member _.M2() =
        printfn $"Instance method M2() on C:  this.id = {id}"

    static member M3(c: C) =
        printfn $"Static method M3(C c) on C:  c.ID = {c.ID}"

    static member M4(c1: C, c2: C) =
        printfn $"Static method M4(C c1, C c2) on C:  c1.ID = {c1.ID}, c2.ID = {c2.ID}"

// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
type D = delegate of C -> unit


type F() =
    member _.M1(c: C) =
        printfn $"Instance method M1(C c) on F:  c.ID = {c.ID}"

    member _.M3(c: C) =
        printfn $"Static method M3(C c) on F:  c.ID = {c.ID}"

    member _.M4(f: F, c: C) =
        printfn $"Static method M4(F f, C c) on F:  c.ID = {c.ID}"

[<EntryPoint>]
let main _ =
    let c1 = C 42
    let c2 = C 1491
    let f1 = F()

    // Instance method with one argument of type C.
    let cmi1 = typeof<C>.GetMethod "M1"
    // Instance method with no arguments.
    let cmi2 = typeof<C>.GetMethod "M2"
    // Static method with one argument of type C.
    let cmi3 = typeof<C>.GetMethod "M3"
    // Static method with two arguments of type C.
    let cmi4 = typeof<C>.GetMethod "M4"

    // Instance method with one argument of type C.
    let fmi1 = typeof<F>.GetMethod "M1"
    // Static method with one argument of type C.
    let fmi3 = typeof<F>.GetMethod "M3"
    // Static method with an argument of type F and an argument
    // of type C.
    let fmi4 = typeof<F>.GetMethod "M4"

    printfn "\nAn instance method on any type, with an argument of type C."
    // D can represent any instance method that exactly matches its
    // signature. Methods on C and F are shown here.
    let d = Delegate.CreateDelegate(typeof<D>, c1, cmi1) :?> D
    d.Invoke c2
    let d =  Delegate.CreateDelegate(typeof<D>, f1, fmi1) :?> D
    d.Invoke c2

    Console.WriteLine("\nAn instance method on C with no arguments.")
    // D can represent an instance method on C that has no arguments
    // in this case, the argument of D represents the hidden first
    // argument of any instance method. The delegate acts like a
    // static method, and an instance of C must be passed each time
    // it is invoked.
    let d = Delegate.CreateDelegate(typeof<D>, null, cmi2) :?> D
    d.Invoke c1

    printfn "\nA static method on any type, with an argument of type C."
    // D can represent any static method with the same signature.
    // Methods on F and C are shown here.
    let d = Delegate.CreateDelegate(typeof<D>, null, cmi3) :?> D
    d.Invoke c1
    let d = Delegate.CreateDelegate(typeof<D>, null, fmi3) :?> D
    d.Invoke c1

    printfn "\nA static method on any type, with an argument of"
    printfn "    that type and an argument of type C."
    // D can represent any static method with one argument of the
    // type the method belongs and a second argument of type C.
    // In this case, the method is closed over the instance of
    // supplied for the its first argument, and acts like an instance
    // method. Methods on F and C are shown here.
    let d = Delegate.CreateDelegate(typeof<D>, c1, cmi4) :?> D
    d.Invoke c2
    let test =
        Delegate.CreateDelegate(typeof<D>, f1, fmi4, false)

    // This final example specifies false for throwOnBindFailure
    // in the call to CreateDelegate, so the variable 'test'
    // contains Nothing if the method fails to bind (for
    // example, if fmi4 happened to represent a method of
    // some class other than F).
    match test with
    | :? D as d ->
        d.Invoke c2
    | _ -> ()
    0

// This code example produces the following output:
//     An instance method on any type, with an argument of type C.
//     Instance method M1(C c) on C:  this.id = 42, c.ID = 1491
//     Instance method M1(C c) on F:  c.ID = 1491
//    
//     An instance method on C with no arguments.
//     Instance method M2() on C:  this.id = 42
//    
//     A static method on any type, with an argument of type C.
//     Static method M3(C c) on C:  c.ID = 42
//     Static method M3(C c) on F:  c.ID = 42
//    
//     A static method on any type, with an argument of
//         that type and an argument of type C.
//     Static method M4(C c1, C c2) on C:  c1.ID = 42, c2.ID = 1491
//     Static method M4(F f, C c) on F:  c.ID = 1491
Imports System.Reflection
Imports System.Security.Permissions

' Declare a delegate type. The object of this code example
' is to show all the methods this delegate can bind to.
'
Public Delegate Sub D(ByVal c As C) 

' Declare two sample classes, C and F. Class C has an ID
' property so instances can be identified.
'
Public Class C

    Private _id As Integer

    Public ReadOnly Property ID() As Integer 
        Get
            Return _id
        End Get
    End Property

    Public Sub New(ByVal newId As Integer) 
        Me._id = newId
    End Sub
    
    Public Sub M1(ByVal c As C) 
        Console.WriteLine("Instance method M1(c As C) on C:  this.id = {0}, c.ID = {1}", _
            Me.id, c.ID)
    End Sub
    
    Public Sub M2() 
        Console.WriteLine("Instance method M2() on C:  this.id = {0}", Me.id)
    End Sub
    
    Public Shared Sub M3(ByVal c As C) 
        Console.WriteLine("Shared method M3(c As C) on C:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M4(ByVal c1 As C, ByVal c2 As C) 
        Console.WriteLine("Shared method M4(c1 As C, c2 As C) on C:  c1.ID = {0}, c2.ID = {1}", _
            c1.ID, c2.ID)
    End Sub
End Class


Public Class F
    
    Public Sub M1(ByVal c As C) 
        Console.WriteLine("Instance method M1(c As C) on F:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M3(ByVal c As C) 
        Console.WriteLine("Shared method M3(c As C) on F:  c.ID = {0}", c.ID)
    End Sub
    
    Public Shared Sub M4(ByVal f As F, ByVal c As C) 
        Console.WriteLine("Shared method M4(f As F, c As C) on F:  c.ID = {0}", c.ID)
    End Sub
End Class

Public Class Example5

    Public Shared Sub Main()

        Dim c1 As New C(42)
        Dim c2 As New C(1491)
        Dim f1 As New F()

        Dim d As D

        ' Instance method with one argument of type C.
        Dim cmi1 As MethodInfo = GetType(C).GetMethod("M1")
        ' Instance method with no arguments.
        Dim cmi2 As MethodInfo = GetType(C).GetMethod("M2")
        ' Shared method with one argument of type C.
        Dim cmi3 As MethodInfo = GetType(C).GetMethod("M3")
        ' Shared method with two arguments of type C.
        Dim cmi4 As MethodInfo = GetType(C).GetMethod("M4")

        ' Instance method with one argument of type C.
        Dim fmi1 As MethodInfo = GetType(F).GetMethod("M1")
        ' Shared method with one argument of type C.
        Dim fmi3 As MethodInfo = GetType(F).GetMethod("M3")
        ' Shared method with an argument of type F and an 
        ' argument of type C.
        Dim fmi4 As MethodInfo = GetType(F).GetMethod("M4")

        Console.WriteLine(vbLf & "An instance method on any type, with an argument of type C.")
        ' D can represent any instance method that exactly matches its
        ' signature. Methods on C and F are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi1), D)
        d(c2)
        d = CType([Delegate].CreateDelegate(GetType(D), f1, fmi1), D)
        d(c2)

        Console.WriteLine(vbLf & "An instance method on C with no arguments.")
        ' D can represent an instance method on C that has no arguments;
        ' in this case, the argument of D represents the hidden first
        ' argument of any instance method. The delegate acts like a 
        ' Shared method, and an instance of C must be passed each time
        ' it is invoked.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi2), D)
        d(c1)

        Console.WriteLine(vbLf & "A Shared method on any type, with an argument of type C.")
        ' D can represent any Shared method with the same signature.
        ' Methods on F and C are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi3), D)
        d(c1)
        d = CType([Delegate].CreateDelegate(GetType(D), Nothing, fmi3), D)
        d(c1)

        Console.WriteLine(vbLf & "A Shared method on any type, with an argument of")
        Console.WriteLine("    that type and an argument of type C.")
        ' D can represent any Shared method with one argument of the
        ' type the method belongs and a second argument of type C.
        ' In this case, the method is closed over the instance of
        ' supplied for the its first argument, and acts like an instance
        ' method. Methods on F and C are shown here.
        '
        d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi4), D)
        d(c2)
        Dim test As [Delegate] =
            [Delegate].CreateDelegate(GetType(D), f1, fmi4, False)

        ' This final example specifies False for throwOnBindFailure 
        ' in the call to CreateDelegate, so the variable 'test'
        ' contains Nothing if the method fails to bind (for 
        ' example, if fmi4 happened to represent a method of  
        ' some class other than F).
        '
        If test IsNot Nothing Then
            d = CType(test, D)
            d(c2)
        End If

    End Sub
End Class

' This code example produces the following output:
'
'An instance method on any type, with an argument of type C.
'Instance method M1(c As C) on C:  this.id = 42, c.ID = 1491
'Instance method M1(c As C) on F:  c.ID = 1491
'
'An instance method on C with no arguments.
'Instance method M2() on C:  this.id = 42
'
'A Shared method on any type, with an argument of type C.
'Shared method M3(c As C) on C:  c.ID = 42
'Shared method M3(c As C) on F:  c.ID = 42
'
'A Shared method on any type, with an argument of
'    that type and an argument of type C.
'Shared method M4(c1 As C, c2 As C) on C:  c1.ID = 42, c2.ID = 1491
'Shared method M4(f As F, c As C) on F:  c.ID = 1491
'

Uyumlu parametre türleri ve dönüş türü

Bu yöntem aşırı yüklemesi kullanılarak oluşturulan bir temsilcinin parametre türleri ve dönüş türü, temsilcinin temsil ettiği yöntemin parametre türleri ve dönüş türüyle uyumlu olmalıdır; türlerin tam olarak eşleşmesi gerekmez.

Temsilci parametresinin türü yöntem parametresinin türünden daha kısıtlayıcıysa, temsilcinin parametresi bir yöntemin ilgili parametresiyle uyumludur, çünkü bu, temsilciye geçirilen bir bağımsız değişkenin yönteme güvenli bir şekilde geçirilebileceğini garanti eder.

Benzer şekilde, bir temsilcinin dönüş türü, yöntemin dönüş türü temsilcinin dönüş türünden daha kısıtlayıcı olduğunda yöntemle uyumludur. Bu, yöntemin dönüş değerinin temsilcinin dönüş türüne güvenli bir şekilde dönüştürülebileceğini garanti eder.

Örneğin, Hashtable türünde bir parametreye ve Object dönüş türüne sahip bir temsilci, Object türünde bir parametreye ve Hashtabletüründe bir dönüş değerine sahip bir yöntemi temsil edebilir.

Temsilcinin gösterebileceği yöntemleri belirleme

CreateDelegate(Type, Object, MethodInfo) aşırı yüklemesi tarafından sağlanan esnekliği düşünmenin bir diğer kullanışlı yolu, belirli bir temsilcinin dört farklı yöntem imzası ve yöntem türü birleşimini (statik ve örnek) temsil edebilmesidir. Dtüründe bir bağımsız değişken içeren bir temsilci türü C düşünün. Aşağıda, D her durumda eşleşmesi gerektiğinden dönüş türünü yoksayarak temsil edebileceği yöntemler açıklanmaktadır.

  • D, örnek yönteminin ait olduğu türe bakılmaksızın Ctüründe tam olarak bir bağımsız değişkeni olan herhangi bir örnek yöntemini temsil edebilir. CreateDelegate çağrıldığında, firstArgumentmethod ait olduğu türün bir örneğidir ve sonuçta elde edilen temsilcinin bu örnek üzerinde kapatılacağı söylenir. (Açıkça, D null referansıysa, firstArgument da bir null referans üzerinden kapatılabilir.)

  • D argümansız bir C örnek metodunu temsil edebilir. CreateDelegate çağrıldığında, firstArgument boş bir başvurudur. Ortaya çıkan delege, açık bir örnek yöntemini temsil eder ve her çağrıldığında bir C örneği sağlanmalıdır.

  • D, Ctüründe bir parametre alan statik bir yöntemi temsil edebilir ve bu yöntem herhangi bir türe ait olabilir. CreateDelegate çağrıldığında, firstArgument boş bir başvurudur. Sonuçta elde edilen temsilci açık bir statik yöntemi temsil eder ve her çağrıldığında bir C örneği sağlanmalıdır.

  • D, F türüne ait olan ve F türünde ve Ctüründe iki bağımsız değişkeni olan statik bir yöntemi temsil edebilir. CreateDelegate çağrıldığında, firstArgument bir Förneğidir. Sonuçta elde edilen temsilci, Förneği üzerinden kapatılan statik bir yöntemi temsil eder. F ve C aynı türde olması durumunda statik yöntemin bu türde iki bağımsız değişkeni olduğunu unutmayın. (Bu durumda, D null başvuruysa firstArgument null başvuru üzerinden kapatılır.)

Açıklamalar

Bu aşırı yükleme statik yöntemler ve açık örnek yöntemi temsilcileri için temsilciler oluşturabilir; diğer bir deyişle, örnek yöntemlerinin gizli ilk bağımsız değişkenini açıkça sağlayan temsilciler. Ayrıntılı bir açıklama için, örneğin veya statik yöntemler için açık veya kapalı temsilcilerin tüm birleşimlerini oluşturmanıza ve isteğe bağlı olarak ilk bağımsız değişkeni belirtmenize olanak tanıyan daha genel CreateDelegate(Type, Object, MethodInfo) yöntem aşırı yüklemesine bakın.

Note

Bu durumda biraz daha hızlı olduğundan, temsilci ilk bağımsız değişkeni üzerinden kapatılmadığında bu yöntem aşırı yüklemesi kullanılmalıdır.

CreateDelegate yöntemleri, belirtilen türde bir temsilci oluşturur.

CreateDelegate(Type, MethodInfo) yöntemi

Bu yöntem aşırı yüklemesi, CreateDelegate(Type, MethodInfo, Boolean) yöntemi aşırı yüklemesini çağırmaya ve trueiçin throwOnBindFailure belirtmeye eşdeğerdir.

Ayrıca bkz.

Şunlara uygulanır

CreateDelegate(Type, Type, String)

Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs
Kaynak:
Delegate.cs

Belirtilen sınıfın belirtilen statik yöntemini temsil eden belirtilen türde bir temsilci oluşturur.

public:
 static Delegate ^ CreateDelegate(Type ^ type, Type ^ target, System::String ^ method);
public static Delegate CreateDelegate(Type type, Type target, string method);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The target method might be removed")]
public static Delegate CreateDelegate(Type type, Type target, string method);
static member CreateDelegate : Type * Type * string -> Delegate
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("The target method might be removed")>]
static member CreateDelegate : Type * Type * string -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Type, method As String) As Delegate

Parametreler

type
Type

Type Oluşturulacak temsilci.

target
Type

Type uygulayan sınıfını temsil edenmethod.

method
String

Temsilcinin temsil etmek üzere olduğu statik yöntemin adı.

Döndürülenler

Belirtilen sınıfın belirtilen statik yöntemini temsil eden belirtilen türün temsilcisi.

Öznitelikler

Özel durumlar

type, null'e eşittir.

-veya-

target, null'e eşittir.

-veya-

method, null'e eşittir.

type devralmıyor MulticastDelegate.

-veya-

type bir RuntimeTypedeğildir. Bkz . Yansımada Çalışma Zamanı Türleri).

-veya-

target bir RuntimeTypedeğildir.

-veya-

target açık bir genel türdür. Yani, özelliği ContainsGenericParameters şeklindedir true.

-veya-

method bir static yöntemi değildir (Visual Basic'de Shared yöntemi).

Invoke yöntemi type bulunamadı.

Çağıranın erişimi methodiçin gerekli izinlere sahip değil.

Açıklamalar

Bu yöntem yalnızca statik yöntemler için temsilciler oluşturur. Örnek yöntemi, sınıfın bir örneğiyle ilişkilendirilmiş bir yöntemdir; statik yöntem, sınıfın kendisiyle ilişkili bir yöntemdir.

Bu yöntem aşırı yüklemesi, için CreateDelegate(Type, Type, String, Boolean, Boolean) ve falseignoreCasedeğerini belirterek true yöntem aşırı yüklemesini throwOnBindFailure çağırmaya eşdeğerdir.

Ayrıca bkz.

Şunlara uygulanır