Delegate.CreateDelegate Metódus
Definíció
Fontos
Egyes információk olyan, kiadás előtti termékekre vonatkoznak, amelyek a kiadásig még jelentősen módosulhatnak. A Microsoft nem vállal kifejezett vagy törvényi garanciát az itt megjelenő információért.
Létrehoz egy megadott típusú meghatalmazottat.
Túlterhelések
| Name | Description |
|---|---|
| CreateDelegate(Type, Object, String, Boolean, Boolean) |
Létrehoz egy megadott típusú delegáltat, amely a megadott osztálypéldányon meghívandó adott példánymetódust jelöli, a megadott kis- és nagybetűk érzékenységével és a kötés meghiúsulásával kapcsolatos megadott viselkedéssel. |
| CreateDelegate(Type, Type, String, Boolean) |
Létrehoz egy megadott típusú delegáltat, amely a megadott osztály megadott statikus metódusát képviseli a megadott kis- és nagybetűk érzékenységével. |
| CreateDelegate(Type, Object, String, Boolean) |
Létrehoz egy megadott típusú delegáltat, amely a megadott osztálypéldányon meghívandó, a megadott kis- és nagybetűkre vonatkozó metódust jelöli. |
| CreateDelegate(Type, Object, MethodInfo, Boolean) |
Létrehoz egy megadott típusú delegáltat, amely a megadott statikus vagy példánymetódusnak felel meg, a megadott első argumentummal és a kötés meghiúsulásának megadott viselkedésével. |
| CreateDelegate(Type, Type, String, Boolean, Boolean) |
Létrehoz egy megadott típusú delegáltat, amely a megadott osztály megadott statikus metódusát képviseli, a megadott kis- és nagybetűk érzékenységével és a kötés meghiúsulásának megadott viselkedésével. |
| CreateDelegate(Type, MethodInfo, Boolean) |
Létrehoz egy megadott típusú delegáltat, amely a megadott statikus metódust képviseli, a kötés meghiúsulása esetén a megadott viselkedéssel. |
| CreateDelegate(Type, Object, String) |
Létrehoz egy megadott típusú delegáltat, amely a megadott osztálypéldányon meghívandó megadott példánymetódust jelöli. |
| CreateDelegate(Type, Object, MethodInfo) |
Létrehoz egy megadott típusú delegáltat, amely a megadott statikus vagy példánymetódusnak felel meg a megadott első argumentummal. |
| CreateDelegate(Type, MethodInfo) |
Létrehoz egy megadott típusú delegáltat, amely a megadott metódust képviseli. |
| CreateDelegate(Type, Type, String) |
Létrehoz egy megadott típusú delegáltat, amely a megadott osztály megadott statikus metódusát jelöli. |
CreateDelegate(Type, Object, String, Boolean, Boolean)
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
Létrehoz egy megadott típusú delegáltat, amely a megadott osztálypéldányon meghívandó adott példánymetódust jelöli, a megadott kis- és nagybetűk érzékenységével és a kötés meghiúsulásával kapcsolatos megadott viselkedéssel.
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
Paraméterek
- target
- Object
A meghívandó osztálypéldány method .
- method
- String
A meghatalmazott által képviselni kívánt példánymetódus neve.
- ignoreCase
- Boolean
Logikai érték, amely azt jelzi, hogy figyelmen kívül kell-e hagyni az esetet a metódus nevének összehasonlításakor.
- throwOnBindFailure
- Boolean
truekivételt kell eredményeznie, ha method nem lehet kötve; ellenkező esetben. false
Válaszok
A megadott típusú delegált, amely a megadott osztálypéldányon meghívandó adott példánymetódust jelöli.
- Attribútumok
Kivételek
type nem örökli MulticastDelegate.
-vagy-
type nem egy RuntimeType. Lásd: Runtime Types in Reflection).
-vagy-
method nem példánymetódus.
-vagy-
method nem lehet kötve, például mert nem található, és throwOnBindFailure az true.
A Invoke metódus type nem található.
A hívó nem rendelkezik a hozzáféréshez methodszükséges engedélyekkel.
Megjegyzések
Ez a metódus csak példánymetódusokhoz hoz létre meghatalmazottakat. A példánymetódus egy osztálypéldányhoz társított metódus; A statikus metódus maga az osztályhoz társított metódus.
Lásd még
A következőre érvényes:
CreateDelegate(Type, Type, String, Boolean)
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
Létrehoz egy megadott típusú delegáltat, amely a megadott osztály megadott statikus metódusát képviseli a megadott kis- és nagybetűk érzékenységével.
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
Paraméterek
- method
- String
A meghatalmazott által képviselni kívánt statikus metódus neve.
- ignoreCase
- Boolean
Logikai érték, amely azt jelzi, hogy figyelmen kívül kell-e hagyni az esetet a metódus nevének összehasonlításakor.
Válaszok
A megadott típusú delegált, amely a megadott osztály megadott statikus metódusát jelöli.
- Attribútumok
Kivételek
type nem örökli MulticastDelegate.
-vagy-
type nem egy RuntimeType. Lásd: Runtime Types in Reflection).
-vagy-
target nem egy RuntimeType.
-vagy-
target egy nyitott általános típus. Vagyis a tulajdonsága ContainsGenericParameters .true
-vagy-
A method nem static metódus (Shared metódus Visual Basic).
-vagy-
method nem lehet kötve, például mert nem található.
A Invoke metódus type nem található.
A hívó nem rendelkezik a hozzáféréshez methodszükséges engedélyekkel.
Megjegyzések
Ez a metódus csak statikus metódusokhoz hoz létre delegáltakat. A példánymetódus egy osztálypéldányhoz társított metódus; A statikus metódus maga az osztályhoz társított metódus.
Ez a metódus túlterhelése egyenértékű a metódus túlterhelésének CreateDelegate(Type, Type, String, Boolean, Boolean) meghívásával, amely true a következőt throwOnBindFailureadja meg: .
Lásd még
A következőre érvényes:
CreateDelegate(Type, Object, String, Boolean)
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
Létrehoz egy megadott típusú delegáltat, amely a megadott osztálypéldányon meghívandó, a megadott kis- és nagybetűkre vonatkozó metódust jelöli.
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
Paraméterek
- target
- Object
A meghívandó osztálypéldány method .
- method
- String
A meghatalmazott által képviselni kívánt példánymetódus neve.
- ignoreCase
- Boolean
Logikai érték, amely azt jelzi, hogy figyelmen kívül kell-e hagyni az esetet a metódus nevének összehasonlításakor.
Válaszok
A megadott típusú delegált, amely a megadott osztálypéldányon meghívandó adott példánymetódust jelöli.
- Attribútumok
Kivételek
type nem örökli MulticastDelegate.
-vagy-
type nem egy RuntimeType. Lásd: Runtime Types in Reflection).
-vagy-
method nem példánymetódus.
-vagy-
method nem lehet kötve, például mert nem található.
A Invoke metódus type nem található.
A hívó nem rendelkezik a hozzáféréshez methodszükséges engedélyekkel.
Megjegyzések
Ez a metódus csak példánymetódusokhoz hoz létre meghatalmazottakat. A példánymetódus egy osztálypéldányhoz társított metódus; A statikus metódus maga az osztályhoz társított metódus.
Ez a metódus túlterhelése egyenértékű a metódus túlterhelésének CreateDelegate(Type, Object, String, Boolean, Boolean) meghívásával, amely true a következőt throwOnBindFailureadja meg: .
Lásd még
A következőre érvényes:
CreateDelegate(Type, Object, MethodInfo, Boolean)
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
Létrehoz egy megadott típusú delegáltat, amely a megadott statikus vagy példánymetódusnak felel meg, a megadott első argumentummal és a kötés meghiúsulásának megadott viselkedésével.
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
Paraméterek
- firstArgument
- Object
Ez Object a meghatalmazott által képviselt metódus első argumentuma. Például a metódusoknak kompatibilisnek kell lenniük a példány típusával.
- method
- MethodInfo
A MethodInfo meghatalmazott által képviselendő statikus vagy példánymetódus leírása.
- throwOnBindFailure
- Boolean
truekivételt kell eredményeznie, ha method nem lehet kötve; ellenkező esetben. false
Válaszok
A megadott típusú delegált, amely a megadott statikus vagy példánymetódust jelöli, vagy null ha throwOnBindFailure igen false , és a meghatalmazott nem köthető hozzá method.
Kivételek
type nem örökli MulticastDelegate.
-vagy-
type nem egy RuntimeType. Lásd: Runtime Types in Reflection).
-vagy-
methodnem lehet megkötni, és throwOnBindFailure az .true
-vagy-
method nem egy RuntimeMethodInfo. Lásd: Runtime Types in Reflection).
A Invoke metódus type nem található.
A hívó nem rendelkezik a hozzáféréshez methodszükséges engedélyekkel.
Megjegyzések
Ez a metódus túlterhelése és a CreateDelegate(Type, Object, MethodInfo) metódus túlterhelése, amely mindig a kötés sikertelenségét okozza, biztosítja a legrugalmasabb módot a meghatalmazottak létrehozására. Ezekkel statikus vagy példánymetelyekhez is létrehozhat delegáltakat első argumentummal vagy anélkül.
Note
Ha nem ad meg első argumentumot, használja a metódus túlterhelését a CreateDelegate(Type, MethodInfo, Boolean) jobb teljesítmény érdekében.
A delegált típusnak és a metódusnak kompatibilis visszatérési típusokkal kell rendelkeznie. Vagyis a method visszatérési típusának átruházhatónak kell lennie a typevisszatérési típusára.
firstArgument– a túlterhelések második paramétere – a meghatalmazott által képviselt metódus első argumentuma. Ha firstArgument van megadva, azt a rendszer minden alkalommal átadja method, amikor a meghatalmazottat meghívják; firstArgument állítólag a meghatalmazotthoz van kötve, és a meghatalmazott az első argumentuma miatt zárva lesz. Ha methodstatic (Shared a Visual Basicben), a meghatalmazott meghívásakor megadott argumentumlista az első kivételével az összes paramétert tartalmazza; ha method egy példánymetódus, akkor a firstArgument a rejtett példányparaméternek továbbítja (c#-ban this, vagy a Visual Basicben Me).
Ha firstArgument van megadva, a method első paraméterének referenciatípusnak kell lennie, és firstArgument kompatibilisnek kell lennie ezzel a típussal.
Important
Ha methodstatic (Shared a Visual Basicben), és első paramétere Object vagy ValueTypetípusú, akkor firstArgument lehet értéktípus. Ebben az esetben a firstArgument automatikusan be van jelölve. Automatikus boxolás nem történik más argumentumok esetében, mint ahogyan egy C# vagy Visual Basic függvényhívásnál történne.
Ha firstArgument null értékű hivatkozás, és method egy példánymetódus, az eredmény a delegált típusú type és a methodaláírásától függ:
- Ha a
typealáírása explicit módon tartalmazza amethodrejtett első paraméterét, akkor a meghatalmazott a nyílt példány metódusát jelöli. Amikor a delegált meghívásra kerül, az argumentumok listájának első argumentuma amethodrejtett példányparaméterének kerül átadásra. - Ha a
methodéstypealáírása egyezik (azaz minden paramétertípus kompatibilis), akkor a delegáltat null értékű hivatkozással kell bezárni. A delegátus meghívása olyan, mintha null példányon hívna meg egy példánymetódust, ami nem különösebben hasznos.
Ha firstArgument null értékű hivatkozás, és method statikus, az eredmény a delegált típusú type és a methodaláírásától függ:
- Ha a
methodéstypealáírása egyezik (vagyis minden paramétertípus kompatibilis), a meghatalmazott azt mondja, hogy egy nyitott statikus metódust jelöl. Ez a statikus metódusok leggyakoribb esete. Ebben az esetben valamivel jobb teljesítményt érhet el a CreateDelegate(Type, MethodInfo) metódus túlterhelésével. - Ha a
typealáírása amethodmásodik paraméterével kezdődik, és a többi paramétertípus kompatibilis, akkor a delegáltat null értékű hivatkozással kell bezárni. A meghatalmazott meghívásakor a függvény null értékű hivatkozást ad át amethodelső paraméterének.
Example
Az alábbi példakód azokat a módszereket mutatja be, amelyek egyetlen delegálási típust jelölhetnek: egy példánymetódushoz zárt, egy példánymetódushoz nyitott, egy statikus metódushoz nyitott, és egy statikus metódushoz zárt.
A példakód két osztályt határoz meg, C és F, valamint egy delegált típusú D egy Ctípusú argumentummal. Az osztályok egyező statikus és példánymetódusokkal rendelkeznek M1, M3és M4, és az osztály C is rendelkezik olyan példánymetódus-M2, amely nem rendelkezik argumentumokkal.
Egy Example nevű harmadik osztály tartalmazza a meghatalmazottakat létrehozó kódot.
- A meghatalmazottak
M1Ctípusú ésFtípusú példánymetódushoz jönnek létre; mindegyik a megfelelő típusú példányon van lezárva. AM1típusú metódusCa kötött példány és az argumentumIDtulajdonságait jeleníti meg. - A
M2típusúCmetódushoz egy delegált jön létre. Ez egy nyílt példánybeli delegált, amelyben a delegált argumentuma a példánymetódus rejtett első argumentumát képviseli. A metódusnak nincsenek más argumentumai. Úgy hívják, mintha statikus módszer lenne. - A delegátumok a
M3statikus metódus és aC, valamint aFtípusokhoz jönnek létre; ezek nyitott statikus delegátumok. - Végül, delegáltak jönnek létre a
M4statikus metódushoz, amely aCtípusú ésFtípushoz tartozik; minden metódus első argumentuma a deklaráló típus, és a típus egy példánya biztosított, így a delegáltak az első argumentumukra zártak. AM4típusú metódusCa kötött példány és az argumentumIDtulajdonságait jeleníti meg.
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
'
Lásd még
A következőre érvényes:
CreateDelegate(Type, Type, String, Boolean, Boolean)
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
Létrehoz egy megadott típusú delegáltat, amely a megadott osztály megadott statikus metódusát képviseli, a megadott kis- és nagybetűk érzékenységével és a kötés meghiúsulásának megadott viselkedésével.
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
Paraméterek
- method
- String
A meghatalmazott által képviselni kívánt statikus metódus neve.
- ignoreCase
- Boolean
Logikai érték, amely azt jelzi, hogy figyelmen kívül kell-e hagyni az esetet a metódus nevének összehasonlításakor.
- throwOnBindFailure
- Boolean
truekivételt kell eredményeznie, ha method nem lehet kötve; ellenkező esetben. false
Válaszok
A megadott típusú delegált, amely a megadott osztály megadott statikus metódusát jelöli.
- Attribútumok
Kivételek
type nem örökli MulticastDelegate.
-vagy-
type nem egy RuntimeType. Lásd: Runtime Types in Reflection).
-vagy-
target nem egy RuntimeType.
-vagy-
target egy nyitott általános típus. Vagyis a tulajdonsága ContainsGenericParameters .true
-vagy-
A method nem static metódus (Shared metódus Visual Basic).
-vagy-
method nem lehet kötve, például mert nem található, és throwOnBindFailure az true.
A Invoke metódus type nem található.
A hívó nem rendelkezik a hozzáféréshez methodszükséges engedélyekkel.
Megjegyzések
Ez a metódus csak statikus metódusokhoz hoz létre delegáltakat. A példánymetódus egy osztálypéldányhoz társított metódus; A statikus metódus maga az osztályhoz társított metódus.
Lásd még
A következőre érvényes:
CreateDelegate(Type, MethodInfo, Boolean)
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
- Forrás:
- Delegate.CoreCLR.cs
Létrehoz egy megadott típusú delegáltat, amely a megadott statikus metódust képviseli, a kötés meghiúsulása esetén a megadott viselkedéssel.
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
Paraméterek
- method
- MethodInfo
A MethodInfo meghatalmazott által képviselendő statikus vagy példánymetódus leírása.
- throwOnBindFailure
- Boolean
truekivételt kell eredményeznie, ha method nem lehet kötve; ellenkező esetben. false
Válaszok
A megadott típusú meghatalmazott, amely a megadott statikus metódust jelöli.
Kivételek
type nem örökli MulticastDelegate.
-vagy-
type nem egy RuntimeType. Lásd: Runtime Types in Reflection).
-vagy-
methodnem lehet megkötni, és throwOnBindFailure az .true
-vagy-
method nem egy RuntimeMethodInfo. Lásd: Runtime Types in Reflection).
A Invoke metódus type nem található.
A hívó nem rendelkezik a hozzáféréshez methodszükséges engedélyekkel.
Példák
Ez a szakasz két példakódot tartalmaz. Az első példa a metódus túlterhelésével létrehozható két típusú delegáltat mutatja be: amelyek példánymetódusokhoz rendelhetők és amelyek statikus metódusokhoz társíthatók.
A második példakód a kompatibilis paramétertípusokat és a visszatérési típusokat mutatja be.
1. példa
Az alábbi példakód bemutatja, hogy a delegált kétféleképpen hozható létre a CreateDelegate metódus ezen túlterhelése segítségével.
Note
A CreateDelegate metódusnak két túlterhelése van, amelyek meghatároznak egy MethodInfo-et, de nem rendelkeznek első argumentummal; a funkciójuk ugyanaz, azzal a különbséggel, hogy az egyik lehetővé teszi annak megadását, hogy sikertelen kötés esetén dobja-e a hibát, míg a másik mindig automatikusan dob hiba esetén. Ez a példakód mindkét túlterhelést használja.
A példa deklarál egy C osztályt egy statikus metódussal (M2), egy példánymetódussal (M1), és két delegált típust: D1 egy C példányt és egy karakterláncot vesz át, míg D2 egy karakterláncot vesz át.
Egy Example nevű másodosztály tartalmazza a meghatalmazottakat létrehozó kódot.
- A
D1példánymetódushoz létrejön egyM1típusú delegált, amely egy nyitott példánymetódust képvisel. A delegált meghívásakor egy példányt kell átadni. - A
D2típusú delegált, amely egy nyitott statikus metódust jelöl, létrejön a statikusM2metódushoz.
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!
'
2. példa
Az alábbi példakód a paramétertípusok és a visszatérési típusok kompatibilitását mutatja be.
A példakód egy Base nevű alaposztályt és egy Derived nevű osztályt határoz meg, amely Baseszármazik. A származtatott osztály egy static nevű Shared (MyMethod visual basic) metódussal rendelkezik, amely egy Base típusú paraméterrel és egy Derivedvisszatérési típussal rendelkezik. A példakód egy Example nevű delegáltat is definiál, amely egy Derived típusú paraméterrel és egy Basevisszatérési típussal rendelkezik.
A példakód azt mutatja be, hogy a Example nevű delegált használható a MyMethodmetódus ábrázolására. A metódus a meghatalmazotthoz köthető, mert:
- A delegált paramétertípusa (
Derived) szigorúbb, mint aMyMethodparamétertípusa (Base), így mindig biztonságosan átadhatja a delegált argumentumátMyMethod. - A
MyMethod(Derived) visszatérési típusa szigorúbb, mint a delegált paramétertípusa (Base), így a metódus visszatérési típusát mindig biztonságosan a delegált visszatérési típusára állíthatja.
A példakód nem hoz létre kimenetet.
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
Megjegyzések
Ez a metódustúlterheltség nyílt statikus metódusdelegáltakat és nyílt példánymetódus-delegáltakat hozhat létre, vagyis olyan meghatalmazottakat, amelyek elérhetővé teszik a példánymetódusok rejtett első argumentumát. Részletes magyarázatért tekintse meg az általánosabb CreateDelegate(Type, Object, MethodInfo, Boolean) metódusterhelést, amely lehetővé teszi a nyílt vagy zárt meghatalmazottak összes kombinációjának létrehozását például statikus vagy statikus metódusokhoz.
Note
Ezt a metódust akkor érdemes túlterhelni, ha a meghatalmazott nincs lezárva az első argumentuma miatt, mert ebben az esetben valamivel gyorsabb.
Lásd még
A következőre érvényes:
CreateDelegate(Type, Object, String)
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
Létrehoz egy megadott típusú delegáltat, amely a megadott osztálypéldányon meghívandó megadott példánymetódust jelöli.
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
Paraméterek
- target
- Object
A meghívandó osztálypéldány method .
- method
- String
A meghatalmazott által képviselni kívánt példánymetódus neve.
Válaszok
A megadott típusú delegált, amely a megadott osztálypéldányon meghívandó adott példánymetódust jelöli.
- Attribútumok
Kivételek
type nem örökli MulticastDelegate.
-vagy-
type nem egy RuntimeType. Lásd: Runtime Types in Reflection).
-vagy-
method nem példánymetódus.
-vagy-
method nem lehet kötve, például mert nem található.
A Invoke metódus type nem található.
A hívó nem rendelkezik a hozzáféréshez methodszükséges engedélyekkel.
Megjegyzések
Ez a metódus csak példánymetódusokhoz hoz létre meghatalmazottakat. A példánymetódus egy osztálypéldányhoz társított metódus; A statikus metódus maga az osztályhoz társított metódus.
Ez a metódus túlterhelése egyenértékű a metódus túlterhelésének CreateDelegate(Type, Object, String, Boolean, Boolean) meghívásával, amely false a metódust ignoreCase és true a metódust throwOnBindFailurehatározza meg.
Lásd még
A következőre érvényes:
CreateDelegate(Type, Object, MethodInfo)
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
Létrehoz egy megadott típusú delegáltat, amely a megadott statikus vagy példánymetódusnak felel meg a megadott első argumentummal.
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
Paraméterek
- firstArgument
- Object
Az objektum, amelyhez a meghatalmazott kötődik, vagy nullmethodstatic (Shared Visual Basic).
- method
- MethodInfo
A MethodInfo meghatalmazott által képviselendő statikus vagy példánymetódus leírása.
Válaszok
A megadott típusú delegált, amely a megadott statikus vagy példánymetódust jelöli.
Kivételek
type nem örökli MulticastDelegate.
-vagy-
type nem egy RuntimeType. Lásd: Runtime Types in Reflection).
-vagy-
method nem lehet kötve.
-vagy-
method nem egy RuntimeMethodInfo. Lásd: Runtime Types in Reflection).
A Invoke metódus type nem található.
A hívó nem rendelkezik a hozzáféréshez methodszükséges engedélyekkel.
Példák
Ez a szakasz két példakódot tartalmaz. Az első példa a metódus túlterhelésével létrehozható két típusú delegáltat mutatja be: amelyek példánymetódusokhoz rendelhetők és amelyek statikus metódusokhoz társíthatók.
A második példakód a kompatibilis paramétertípusokat és a visszatérési típusokat mutatja be.
1. példa
Az alábbi példakód bemutatja, hogy a delegált kétféleképpen hozható létre a CreateDelegate metódus ezen túlterhelése segítségével.
Note
A CreateDelegate metódusnak két túlterhelése van, amelyek meghatároznak egy MethodInfo-et, de nem rendelkeznek első argumentummal; a funkciójuk ugyanaz, azzal a különbséggel, hogy az egyik lehetővé teszi annak megadását, hogy sikertelen kötés esetén dobja-e a hibát, míg a másik mindig automatikusan dob hiba esetén. Ez a példakód mindkét túlterhelést használja.
A példa deklarál egy C osztályt egy statikus metódussal (M2), egy példánymetódussal (M1), és két delegált típust: D1 egy C példányt és egy karakterláncot vesz át, míg D2 egy karakterláncot vesz át.
Egy Example nevű másodosztály tartalmazza a meghatalmazottakat létrehozó kódot.
- A
D1példánymetódushoz létrejön egyM1típusú delegált, amely egy nyitott példánymetódust képvisel. A delegált meghívásakor egy példányt kell átadni. - A
D2típusú delegált, amely egy nyitott statikus metódust jelöl, létrejön a statikusM2metódushoz.
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!
'
2. példa
Az alábbi példakód a paramétertípusok és a visszatérési típusok kompatibilitását mutatja be.
A példakód egy Base nevű alaposztályt és egy Derived nevű osztályt határoz meg, amely Baseszármazik. A származtatott osztály egy static nevű Shared (MyMethod visual basic) metódussal rendelkezik, amely egy Base típusú paraméterrel és egy Derivedvisszatérési típussal rendelkezik. A példakód egy Example nevű delegáltat is definiál, amely egy Derived típusú paraméterrel és egy Basevisszatérési típussal rendelkezik.
A példakód azt mutatja be, hogy a Example nevű delegált használható a MyMethodmetódus ábrázolására. A metódus a meghatalmazotthoz köthető, mert:
- A delegált paramétertípusa (
Derived) szigorúbb, mint aMyMethodparamétertípusa (Base), így mindig biztonságosan átadhatja a delegált argumentumátMyMethod. - A
MyMethod(Derived) visszatérési típusa szigorúbb, mint a delegált paramétertípusa (Base), így a metódus visszatérési típusát mindig biztonságosan a delegált visszatérési típusára állíthatja.
A példakód nem hoz létre kimenetet.
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) és CreateDelegate(Type, Object, MethodInfo, Boolean) metódusok
Ennek a két túlterhelésnek a funkciója ugyanaz, kivéve, hogy az egyik lehetővé teszi annak megadását, hogy dobjon-e hibát, ha a kötés sikertelen, míg a másik mindig dob hibát.
A delegált típusnak és a metódusnak kompatibilis visszatérési típusokkal kell rendelkeznie. Vagyis a method visszatérési típusának átruházhatónak kell lennie a typevisszatérési típusára.
firstArgument– a túlterhelések második paramétere – a meghatalmazott által képviselt metódus első argumentuma. Ha firstArgument van megadva, azt a rendszer minden alkalommal átadja method, amikor a meghatalmazottat meghívják; firstArgument állítólag a meghatalmazotthoz van kötve, és a meghatalmazott az első argumentuma miatt zárva lesz. Ha methodstatic (Shared a Visual Basicben), a meghatalmazott meghívásakor megadott argumentumlista az első kivételével az összes paramétert tartalmazza; ha method egy példánymetódus, akkor a firstArgument a rejtett példányparaméternek továbbítja (c#-ban this, vagy a Visual Basicben Me).
Ha firstArgument van megadva, a method első paraméterének referenciatípusnak kell lennie, és firstArgument kompatibilisnek kell lennie ezzel a típussal.
Important
Ha methodstatic (Shared a Visual Basicben), és első paramétere Object vagy ValueTypetípusú, akkor firstArgument lehet értéktípus. Ebben az esetben a firstArgument automatikusan be van jelölve. Automatikus boxolás nem történik más argumentumok esetében, mint ahogyan egy C# vagy Visual Basic függvényhívásnál történne.
Ha firstArgument null értékű hivatkozás, és method egy példánymetódus, az eredmény a delegált típusú type és a methodaláírásától függ:
- Ha a
typealáírása explicit módon tartalmazza amethodrejtett első paraméterét, akkor a meghatalmazott a nyílt példány metódusát jelöli. Amikor a delegált meghívásra kerül, az argumentumok listájának első argumentuma amethodrejtett példányparaméterének kerül átadásra. - Ha a
methodéstypealáírása egyezik (azaz minden paramétertípus kompatibilis), akkor a delegáltat null értékű hivatkozással kell bezárni. A delegátus meghívása olyan, mintha null példányon hívna meg egy példánymetódust, ami nem különösebben hasznos.
Ha firstArgument null értékű hivatkozás, és method statikus, az eredmény a delegált típusú type és a methodaláírásától függ:
- Ha a
methodéstypealáírása egyezik (vagyis minden paramétertípus kompatibilis), a meghatalmazott azt mondja, hogy egy nyitott statikus metódust jelöl. Ez a statikus metódusok leggyakoribb esete. Ebben az esetben valamivel jobb teljesítményt érhet el a CreateDelegate(Type, MethodInfo) metódus túlterhelésével. - Ha a
typealáírása amethodmásodik paraméterével kezdődik, és a többi paramétertípus kompatibilis, akkor a delegáltat null értékű hivatkozással kell bezárni. A meghatalmazott meghívásakor a függvény null értékű hivatkozást ad át amethodelső paraméterének.
Example
Az alábbi példakód azokat a módszereket mutatja be, amelyek egyetlen delegálási típust jelölhetnek: egy példánymetódushoz zárt, egy példánymetódushoz nyitott, egy statikus metódushoz nyitott, és egy statikus metódushoz zárt.
A példakód két osztályt határoz meg, C és F, valamint egy delegált típusú D egy Ctípusú argumentummal. Az osztályok egyező statikus és példánymetódusokkal rendelkeznek M1, M3és M4, és az osztály C is rendelkezik olyan példánymetódus-M2, amely nem rendelkezik argumentumokkal.
Egy Example nevű harmadik osztály tartalmazza a meghatalmazottakat létrehozó kódot.
- A meghatalmazottak
M1Ctípusú ésFtípusú példánymetódushoz jönnek létre; mindegyik a megfelelő típusú példányon van lezárva. AM1típusú metódusCa kötött példány és az argumentumIDtulajdonságait jeleníti meg. - A
M2típusúCmetódushoz egy delegált jön létre. Ez egy nyílt példánybeli delegált, amelyben a delegált argumentuma a példánymetódus rejtett első argumentumát képviseli. A metódusnak nincsenek más argumentumai. Úgy hívják, mintha statikus módszer lenne. - A delegátumok a
M3statikus metódus és aC, valamint aFtípusokhoz jönnek létre; ezek nyitott statikus delegátumok. - Végül, delegáltak jönnek létre a
M4statikus metódushoz, amely aCtípusú ésFtípushoz tartozik; minden metódus első argumentuma a deklaráló típus, és a típus egy példánya biztosított, így a delegáltak az első argumentumukra zártak. AM4típusú metódusCa kötött példány és az argumentumIDtulajdonságait jeleníti meg.
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
'
Kompatibilis paramétertípusok és visszatérési típus
Az ezzel a metódussal létrehozott delegált paramétertípusainak és visszatérési típusának kompatibilisnek kell lennie a delegált által képviselt paramétertípussal és visszatérési típussal; a típusoknak nem kell pontosan egyezniük.
A meghatalmazott paramétere kompatibilis a metódus megfelelő paraméterével, ha a delegálási paraméter típusa szigorúbb, mint a metódusparaméter típusa, mivel ez garantálja, hogy a delegáltnak átadott argumentum biztonságosan átadható a metódusnak.
Hasonlóképpen, a delegált visszatérési típusa kompatibilis a metódus visszatérési típusával, ha a metódus visszatérési típusa korlátozóbb, mint a delegált visszatérési típusa, mivel ez garantálja, hogy a metódus visszatérési értéke biztonságosan átvehető a delegált visszatérési típusára.
Egy Hashtable típusú paraméterrel és a Object visszatérési típusával rendelkező delegáltak például olyan metódust képviselhetnek, amely Object típusú paraméterrel és Hashtabletípusú visszatérési értékkel rendelkezik.
Határozza meg, hogy a meghatalmazott milyen módszereket jelölhet
A CreateDelegate(Type, Object, MethodInfo) túlterhelés által biztosított rugalmasság másik hasznos módja, hogy bármely adott meghatalmazott a metódus-aláírás és a metódustípus négy különböző kombinációját (statikus és példány) képviselheti. Fontoljon meg egy D típusú delegáltat, amelynek egy Ctípusú argumentuma van. Az alábbiakban az D által képviselhető metódusokat ismertetjük, figyelmen kívül hagyva a visszatérési típust, mivel annak minden esetben meg kell egyeznie.
Dbármely olyan példánymetódust jelölhet, amelynek pontosan egyCtípusú argumentuma van, függetlenül attól, hogy a példánymetódus milyen típushoz tartozik. Amikor a CreateDelegate meghívásra kerül, afirstArgumentamethodtartozó típus egy példánya, és az eredményként kapott delegált zárt lesz ahhoz a példányhoz. (Triviálisan aDnull hivatkozással is bezárható, hafirstArgumentnull hivatkozás.)Daz argumentumokat nem tartalmazóCegy példánymetódusát jelölheti. Amikor a CreateDelegate meghívásra kerül, afirstArgumentnull referencia. Az eredményként kapott delegált egy nyitott példánymetódust jelöl, és minden egyes meghíváskor meg kell adni egyC-példányt.Dolyan statikus metódust jelölhet, amely egyCtípusú argumentumot vesz fel, és ez a metódus bármilyen típushoz tartozhat. Amikor a CreateDelegate meghívásra kerül, afirstArgumentnull referencia. Az eredményként kapott meghatalmazott egy nyitott statikus metódust jelöl, és minden egyes meghíváskor meg kell adni egyC-példányt.Dolyan statikus metódust jelölhet, amelyFtípushoz tartozik, és két argumentumot is tartalmazhat,Ftípusú ésCtípusú. A CreateDelegate meghívásakor afirstArgumentaFegy példánya. Az eredményként kapott delegált egy statikus metódust jelöl, amely aFadott példánya felett van lezárva. Vegye figyelembe, hogy abban az esetben, haFésCazonos típusúak, a statikus metódusnak két argumentuma van. Ebben az esetbenDnull hivatkozással van lezárva, hafirstArgumentnull hivatkozás.
Megjegyzések
A metódus túlterhelésének meghívása egyenértékű a metódus túlterhelésének CreateDelegate(Type, Object, MethodInfo, Boolean) meghívásával és a metódus megadásával truethrowOnBindFailure. Ez a két túlterhelés biztosítja a legrugalmasabb módot a meghatalmazottak létrehozására. Ezekkel statikus vagy példánymetodusokhoz is létrehozhat meghatalmazottakat, és opcionálisan megadhatja az első argumentumot.
Note
Ha nem ad meg első argumentumot, használja a metódus túlterhelését a CreateDelegate(Type, MethodInfo) jobb teljesítmény érdekében.
A CreateDelegate metódusok egy megadott típusú delegáltat hoznak létre.
CreateDelegate(Type, MethodInfo) módszer
Ennek a metódusnak a túlterhelése egyenértékű a CreateDelegate(Type, MethodInfo, Boolean) metódus túlterhelésének meghívásával, és azzal, hogy a trueszámára meghatározza a throwOnBindFailure-et.
Lásd még
A következőre érvényes:
CreateDelegate(Type, MethodInfo)
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
Létrehoz egy megadott típusú delegáltat, amely a megadott metódust képviseli.
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
Paraméterek
- method
- MethodInfo
A MethodInfo meghatalmazott által képviselendő statikus vagy példánymetódus leírása.
Válaszok
A megadott metódust képviselő meghatalmazott.
Kivételek
type nem örökli MulticastDelegate.
-vagy-
type nem egy RuntimeType. Lásd: Runtime Types in Reflection).
-vagy-
method nem lehet kötve.
-vagy-
method nem egy RuntimeMethodInfo. Lásd: Runtime Types in Reflection).
A Invoke metódus type nem található.
A hívó nem rendelkezik a hozzáféréshez methodszükséges engedélyekkel.
Példák
Ez a szakasz két példakódot tartalmaz. Az első példa a metódus túlterhelésével létrehozható két típusú delegáltat mutatja be: amelyek példánymetódusokhoz rendelhetők és amelyek statikus metódusokhoz társíthatók.
A második példakód a kompatibilis paramétertípusokat és a visszatérési típusokat mutatja be.
1. példa
Az alábbi példakód bemutatja, hogy a delegált kétféleképpen hozható létre a CreateDelegate metódus ezen túlterhelése segítségével.
Note
A CreateDelegate metódusnak két túlterhelése van, amelyek meghatároznak egy MethodInfo-et, de nem rendelkeznek első argumentummal; a funkciójuk ugyanaz, azzal a különbséggel, hogy az egyik lehetővé teszi annak megadását, hogy sikertelen kötés esetén dobja-e a hibát, míg a másik mindig automatikusan dob hiba esetén. Ez a példakód mindkét túlterhelést használja.
A példa deklarál egy C osztályt egy statikus metódussal (M2), egy példánymetódussal (M1), és két delegált típust: D1 egy C példányt és egy karakterláncot vesz át, míg D2 egy karakterláncot vesz át.
Egy Example nevű másodosztály tartalmazza a meghatalmazottakat létrehozó kódot.
- A
D1példánymetódushoz létrejön egyM1típusú delegált, amely egy nyitott példánymetódust képvisel. A delegált meghívásakor egy példányt kell átadni. - A
D2típusú delegált, amely egy nyitott statikus metódust jelöl, létrejön a statikusM2metódushoz.
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!
'
2. példa
Az alábbi példakód a paramétertípusok és a visszatérési típusok kompatibilitását mutatja be.
A példakód egy Base nevű alaposztályt és egy Derived nevű osztályt határoz meg, amely Baseszármazik. A származtatott osztály egy static nevű Shared (MyMethod visual basic) metódussal rendelkezik, amely egy Base típusú paraméterrel és egy Derivedvisszatérési típussal rendelkezik. A példakód egy Example nevű delegáltat is definiál, amely egy Derived típusú paraméterrel és egy Basevisszatérési típussal rendelkezik.
A példakód azt mutatja be, hogy a Example nevű delegált használható a MyMethodmetódus ábrázolására. A metódus a meghatalmazotthoz köthető, mert:
- A delegált paramétertípusa (
Derived) szigorúbb, mint aMyMethodparamétertípusa (Base), így mindig biztonságosan átadhatja a delegált argumentumátMyMethod. - A
MyMethod(Derived) visszatérési típusa szigorúbb, mint a delegált paramétertípusa (Base), így a metódus visszatérési típusát mindig biztonságosan a delegált visszatérési típusára állíthatja.
A példakód nem hoz létre kimenetet.
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) és CreateDelegate(Type, Object, MethodInfo, Boolean) metódusok
Ennek a két túlterhelésnek a funkciója ugyanaz, kivéve, hogy az egyik lehetővé teszi annak megadását, hogy dobjon-e hibát, ha a kötés sikertelen, míg a másik mindig dob hibát.
A delegált típusnak és a metódusnak kompatibilis visszatérési típusokkal kell rendelkeznie. Vagyis a method visszatérési típusának átruházhatónak kell lennie a typevisszatérési típusára.
firstArgument– a túlterhelések második paramétere – a meghatalmazott által képviselt metódus első argumentuma. Ha firstArgument van megadva, azt a rendszer minden alkalommal átadja method, amikor a meghatalmazottat meghívják; firstArgument állítólag a meghatalmazotthoz van kötve, és a meghatalmazott az első argumentuma miatt zárva lesz. Ha methodstatic (Shared a Visual Basicben), a meghatalmazott meghívásakor megadott argumentumlista az első kivételével az összes paramétert tartalmazza; ha method egy példánymetódus, akkor a firstArgument a rejtett példányparaméternek továbbítja (c#-ban this, vagy a Visual Basicben Me).
Ha firstArgument van megadva, a method első paraméterének referenciatípusnak kell lennie, és firstArgument kompatibilisnek kell lennie ezzel a típussal.
Important
Ha methodstatic (Shared a Visual Basicben), és első paramétere Object vagy ValueTypetípusú, akkor firstArgument lehet értéktípus. Ebben az esetben a firstArgument automatikusan be van jelölve. Automatikus boxolás nem történik más argumentumok esetében, mint ahogyan egy C# vagy Visual Basic függvényhívásnál történne.
Ha firstArgument null értékű hivatkozás, és method egy példánymetódus, az eredmény a delegált típusú type és a methodaláírásától függ:
- Ha a
typealáírása explicit módon tartalmazza amethodrejtett első paraméterét, akkor a meghatalmazott a nyílt példány metódusát jelöli. Amikor a delegált meghívásra kerül, az argumentumok listájának első argumentuma amethodrejtett példányparaméterének kerül átadásra. - Ha a
methodéstypealáírása egyezik (azaz minden paramétertípus kompatibilis), akkor a delegáltat null értékű hivatkozással kell bezárni. A delegátus meghívása olyan, mintha null példányon hívna meg egy példánymetódust, ami nem különösebben hasznos.
Ha firstArgument null értékű hivatkozás, és method statikus, az eredmény a delegált típusú type és a methodaláírásától függ:
- Ha a
methodéstypealáírása egyezik (vagyis minden paramétertípus kompatibilis), a meghatalmazott azt mondja, hogy egy nyitott statikus metódust jelöl. Ez a statikus metódusok leggyakoribb esete. Ebben az esetben valamivel jobb teljesítményt érhet el a CreateDelegate(Type, MethodInfo) metódus túlterhelésével. - Ha a
typealáírása amethodmásodik paraméterével kezdődik, és a többi paramétertípus kompatibilis, akkor a delegáltat null értékű hivatkozással kell bezárni. A meghatalmazott meghívásakor a függvény null értékű hivatkozást ad át amethodelső paraméterének.
Example
Az alábbi példakód azokat a módszereket mutatja be, amelyek egyetlen delegálási típust jelölhetnek: egy példánymetódushoz zárt, egy példánymetódushoz nyitott, egy statikus metódushoz nyitott, és egy statikus metódushoz zárt.
A példakód két osztályt határoz meg, C és F, valamint egy delegált típusú D egy Ctípusú argumentummal. Az osztályok egyező statikus és példánymetódusokkal rendelkeznek M1, M3és M4, és az osztály C is rendelkezik olyan példánymetódus-M2, amely nem rendelkezik argumentumokkal.
Egy Example nevű harmadik osztály tartalmazza a meghatalmazottakat létrehozó kódot.
- A meghatalmazottak
M1Ctípusú ésFtípusú példánymetódushoz jönnek létre; mindegyik a megfelelő típusú példányon van lezárva. AM1típusú metódusCa kötött példány és az argumentumIDtulajdonságait jeleníti meg. - A
M2típusúCmetódushoz egy delegált jön létre. Ez egy nyílt példánybeli delegált, amelyben a delegált argumentuma a példánymetódus rejtett első argumentumát képviseli. A metódusnak nincsenek más argumentumai. Úgy hívják, mintha statikus módszer lenne. - A delegátumok a
M3statikus metódus és aC, valamint aFtípusokhoz jönnek létre; ezek nyitott statikus delegátumok. - Végül, delegáltak jönnek létre a
M4statikus metódushoz, amely aCtípusú ésFtípushoz tartozik; minden metódus első argumentuma a deklaráló típus, és a típus egy példánya biztosított, így a delegáltak az első argumentumukra zártak. AM4típusú metódusCa kötött példány és az argumentumIDtulajdonságait jeleníti meg.
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
'
Kompatibilis paramétertípusok és visszatérési típus
Az ezzel a metódussal létrehozott delegált paramétertípusainak és visszatérési típusának kompatibilisnek kell lennie a delegált által képviselt paramétertípussal és visszatérési típussal; a típusoknak nem kell pontosan egyezniük.
A meghatalmazott paramétere kompatibilis a metódus megfelelő paraméterével, ha a delegálási paraméter típusa szigorúbb, mint a metódusparaméter típusa, mivel ez garantálja, hogy a delegáltnak átadott argumentum biztonságosan átadható a metódusnak.
Hasonlóképpen, a delegált visszatérési típusa kompatibilis a metódus visszatérési típusával, ha a metódus visszatérési típusa korlátozóbb, mint a delegált visszatérési típusa, mivel ez garantálja, hogy a metódus visszatérési értéke biztonságosan átvehető a delegált visszatérési típusára.
Egy Hashtable típusú paraméterrel és a Object visszatérési típusával rendelkező delegáltak például olyan metódust képviselhetnek, amely Object típusú paraméterrel és Hashtabletípusú visszatérési értékkel rendelkezik.
Határozza meg, hogy a meghatalmazott milyen módszereket jelölhet
A CreateDelegate(Type, Object, MethodInfo) túlterhelés által biztosított rugalmasság másik hasznos módja, hogy bármely adott meghatalmazott a metódus-aláírás és a metódustípus négy különböző kombinációját (statikus és példány) képviselheti. Fontoljon meg egy D típusú delegáltat, amelynek egy Ctípusú argumentuma van. Az alábbiakban az D által képviselhető metódusokat ismertetjük, figyelmen kívül hagyva a visszatérési típust, mivel annak minden esetben meg kell egyeznie.
Dbármely olyan példánymetódust jelölhet, amelynek pontosan egyCtípusú argumentuma van, függetlenül attól, hogy a példánymetódus milyen típushoz tartozik. Amikor a CreateDelegate meghívásra kerül, afirstArgumentamethodtartozó típus egy példánya, és az eredményként kapott delegált zárt lesz ahhoz a példányhoz. (Triviálisan aDnull hivatkozással is bezárható, hafirstArgumentnull hivatkozás.)Daz argumentumokat nem tartalmazóCegy példánymetódusát jelölheti. Amikor a CreateDelegate meghívásra kerül, afirstArgumentnull referencia. Az eredményként kapott delegált egy nyitott példánymetódust jelöl, és minden egyes meghíváskor meg kell adni egyC-példányt.Dolyan statikus metódust jelölhet, amely egyCtípusú argumentumot vesz fel, és ez a metódus bármilyen típushoz tartozhat. Amikor a CreateDelegate meghívásra kerül, afirstArgumentnull referencia. Az eredményként kapott meghatalmazott egy nyitott statikus metódust jelöl, és minden egyes meghíváskor meg kell adni egyC-példányt.Dolyan statikus metódust jelölhet, amelyFtípushoz tartozik, és két argumentumot is tartalmazhat,Ftípusú ésCtípusú. A CreateDelegate meghívásakor afirstArgumentaFegy példánya. Az eredményként kapott delegált egy statikus metódust jelöl, amely aFadott példánya felett van lezárva. Vegye figyelembe, hogy abban az esetben, haFésCazonos típusúak, a statikus metódusnak két argumentuma van. Ebben az esetbenDnull hivatkozással van lezárva, hafirstArgumentnull hivatkozás.
Megjegyzések
Ez a túlterhelés statikus metódusokhoz és nyílt példánymetódus-delegáltakhoz hozhat létre delegáltakat; vagyis olyan meghatalmazottak, amelyek kifejezetten megadják a példány metódusainak rejtett első argumentumát. Részletes magyarázatért tekintse meg az általánosabb CreateDelegate(Type, Object, MethodInfo) metódusterhelést, amely lehetővé teszi a nyitott vagy zárt meghatalmazottak összes kombinációjának létrehozását például statikus vagy statikus metódusok esetében, és opcionálisan az első argumentum megadását.
Note
Ezt a metódust akkor érdemes túlterhelni, ha a meghatalmazott nincs lezárva az első argumentuma miatt, mert ebben az esetben valamivel gyorsabb.
A CreateDelegate metódusok egy megadott típusú delegáltat hoznak létre.
CreateDelegate(Type, MethodInfo) módszer
Ennek a metódusnak a túlterhelése egyenértékű a CreateDelegate(Type, MethodInfo, Boolean) metódus túlterhelésének meghívásával, és azzal, hogy a trueszámára meghatározza a throwOnBindFailure-et.
Lásd még
A következőre érvényes:
CreateDelegate(Type, Type, String)
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
- Forrás:
- Delegate.cs
Létrehoz egy megadott típusú delegáltat, amely a megadott osztály megadott statikus metódusát jelöli.
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
Paraméterek
- method
- String
A meghatalmazott által képviselni kívánt statikus metódus neve.
Válaszok
A megadott típusú delegált, amely a megadott osztály megadott statikus metódusát jelöli.
- Attribútumok
Kivételek
type nem örökli MulticastDelegate.
-vagy-
type nem egy RuntimeType. Lásd: Runtime Types in Reflection).
-vagy-
target nem egy RuntimeType.
-vagy-
target egy nyitott általános típus. Vagyis a tulajdonsága ContainsGenericParameters .true
-vagy-
A method nem static metódus (Shared metódus Visual Basic).
A Invoke metódus type nem található.
A hívó nem rendelkezik a hozzáféréshez methodszükséges engedélyekkel.
Megjegyzések
Ez a metódus csak statikus metódusokhoz hoz létre delegáltakat. A példánymetódus egy osztálypéldányhoz társított metódus; A statikus metódus maga az osztályhoz társított metódus.
Ez a metódus túlterhelése egyenértékű a metódus túlterhelésének CreateDelegate(Type, Type, String, Boolean, Boolean) meghívásával, amely false a metódust ignoreCase és true a metódust throwOnBindFailurehatározza meg.