|
Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
|
Tradução
Original
|
Método Delegate.CreateDelegate (Type, MethodInfo)
Assembly: mscorlib (em mscorlib.dll)
Parâmetros
- type
- Tipo: System.Type
The Type do delegado para criar.
- method
- Tipo: System.Reflection.MethodInfo
The MethodInfo descrevendo o estático ou método é o delegado representar da instância. Há suporte para apenas métodos estático no .NET estrutura versão 1.0 e 1.1.
Valor de retorno
Tipo: System.Delegate| Exceção | Condição |
|---|---|
| ArgumentNullException | |
| ArgumentException | |
| MissingMethodException | |
| MethodAccessException |
Observação: |
|---|
Observação: |
|---|
Compatível com tipos de parâmetros e o tipo de retorno
Exemplo 1
Observação: |
|---|
Um delegado do tipo D1, que representa um método de instância aberta é criada para o método de instância M1. Uma instância deve ser passada quando o delegado é chamado. Um delegado do tipo D2, que representa um método estático em aberto, é criada para o método estático M2.
using System; using System.Reflection; using System.Security.Permissions; // Declare three delegate types for demonstrating the combinations// of static versus instance methods and open versus closed// delegates.//publicdelegatevoid D1(C c, string s); publicdelegatevoid D2(string s); publicdelegatevoid D3(); // A sample class with an instance method and a static method.//publicclass C { privateint id; public C(int id) { this.id = id; } publicvoid M1(string s) { Console.WriteLine("Instance method M1 on C: id = {0}, s = {1}", this.id, s); } publicstaticvoid M2(string s) { Console.WriteLine("Static method M2 on C: s = {0}", s); } } publicclass Example { publicstaticvoid 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 static 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! */
Exemplo 2
O tipo de parâmetro do delegado (Derived) é mais restritivo que o tipo de parâmetro MyMethod (Base), para que sempre seja seguro passar o argumento do representante para MyMethod. O tipo de retorno de MyMethod (Derived) é mais restritivo que o tipo de parâmetro de (delegadoBase), para que sempre seja seguro para converter o tipo de retorno do método para o tipo de retorno do delegado.
using System; using System.Reflection; // Define two classes to use in the demonstration, a base class and // a class that derives from it.//publicclass Base {} publicclass 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. //publicstatic Derived MyMethod(Base arg) { Base dummy = arg; returnnew Derived(); } } // Define a delegate that takes an instance of Derived and returns an// instance of Base.//publicdelegate Base Example(Derived arg); class Test { publicstaticvoid 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 covariance of parameter types and contravariance// 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). // Example ex = (Example) Delegate.CreateDelegate(typeof(Example), minfo); // Execute MyMethod using the delegate Example.// Base b = ex(new Derived()); } }
- ReflectionPermission
para acessar um método não público quando o conjunto de concessão do método não público está restrito a do chamador conceda conjunto ou um subconjunto deles. Enumeração associada: ReflectionPermissionFlag.RestrictedMemberAccess - ReflectionPermission
para acessar um método não-públicos independentemente de sua concessão definido. Enumeração associada: ReflectionPermissionFlag.MemberAccess - ReflectionPermission
Quando chamado tardia através de mecanismos sistema autônomo Type.InvokeMember. Enumeração associada: ReflectionPermissionFlag.MemberAccess.
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98
o.NET Framework e.NET Compact Framework não oferecem suporte a todas as versões de cada plataforma. Para obter uma lista de versões suportadas, consulte Requisitos de sistema do .NET framework.
Observação: