2009-07-07 107 views
2

我正在使用反射類來調用某些其他DLL上的某些方法。 而其中一種方法的參數是委託類型。如何將委託轉換爲C#中的對象?

我想用反射來調用這個方法。 所以我需要傳遞函數參數作爲對象數組,但我找不到任何關於 如何將委託轉換爲對象。

預先感謝

+0

你能後的你想轉換一個什麼樣的代碼?這將允許人們真正準確地回答 – 2009-07-07 08:17:04

回答

5

委託是一個對象。只需像通常那樣創建預期的委託,然後將它傳遞給參數數組。這是一個虛構的例子:代表

class Mathematician { 
    public delegate int MathMethod(int a, int b); 

    public int DoMaths(int a, int b, MathMethod mathMethod) { 
     return mathMethod(a, b); 
    } 
} 

[Test] 
public void Test() { 
    var math = new Mathematician(); 
    Mathematician.MathMethod addition = (a, b) => a + b; 
    var method = typeof(Mathematician).GetMethod("DoMaths"); 
    var result = method.Invoke(math, new object[] { 1, 2, addition }); 
    Assert.AreEqual(3, result); 
} 
+0

簡單的馬特,我想你忘了包括一個解釋性的例子! – 2009-07-07 08:17:38

1

實例是對象,所以此代碼(C#3的風格):

Predicate<int> p = (i)=> i >= 42; 

Object[] arrayOfObject = new object[] { p }; 

希望它能幫助!

塞德里克

1

下面是一個例子:

class Program 
{ 
    public delegate void TestDel(); 

    public static void ToInvoke(TestDel testDel) 
    { 
     testDel(); 
    } 

    public static void Test() 
    { 
     Console.WriteLine("hello world"); 
    } 

    static void Main(string[] args) 
    { 
     TestDel testDel = Program.Test; 
     typeof(Program).InvokeMember(
      "ToInvoke", 
      BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, 
      null, 
      null, 
      new object[] { testDel }); 
    } 
} 
+0

感謝您的回覆。 我試過你的方式,我通過相同的委託,這是在外部的DLL,但有怪異的異常說: 參數異常: 類型爲「namespace.class.delegate」的對象不能轉換爲「namespace.class.delegate」 – AFgone 2009-07-07 12:23:47

1

我不知道如果我正確地理解你的問題,但你可以從這樣的方法創建一個委託對象:

public class Test 
{ 
    public static void Method() {} 
} 

然後你創建一個這樣的代理對象:

Delegate myDelegate = new Delegate(Test.Method); 
0

你可以看到一個委託爲變量類型「功能」。代表描述匹配函數的參數和返回值。

delegate void Foo(int a); // here a new delegate obj type Foo has been declared 

上面的例子中允許「富」被用作一種數據類型,可以與Foo類型數據類型的變量相匹配的唯一允許的對象是具有相同簽名如此方法:

void MyFunction(int x);  

Foo D = MyFunction; // this is OK 

void MyOtherFunction(string x); 

Foo D = MyOtherFunction; // will yield an error since not same signature. 

一旦分配方法的委託,可以通過委託調用方法:

​​
相關問題