2008-12-30 34 views
5

có ai biết cách gọi một phương thức chung của một lớp cơ sở với CodeDom không?CodeDom - Gọi một phương thức chung

Tôi không có vấn đề gì khi gọi phương thức chuẩn, nhưng tôi không thể tìm thấy giải pháp để gọi chung.

Mã tôi sử dụng để gọi các phương pháp tiêu chuẩn lớp cơ sở getInstance:

CodeAssignStatement assignStatement = new CodeAssignStatement(
    new CodeVariableReferenceExpression("instance"), 
    new CodeMethodInvokeExpression(
     new CodeThisReferenceExpression(), 
     "GetInstance", 
     new CodeExpression[] { new CodeVariableReferenceExpression("instance") } 
    )); 

Trả lời

11

Bạn có thể tìm thấy câu trả lời của bạn here trong MSDN:

cuộn xuống đến C# ví dụ (CodeDomGenericsDemo).

Một phương pháp chung được tạo ra:

public virtual void Print<S, T>() 
      where S : new() 
     { 
      Console.WriteLine(default(T)); 
      Console.WriteLine(default(S)); 
     } 

và sau đó thực hiện trong ví dụ:

dict.Print<decimal, int>(); 

Mã này để tạo ra các cuộc gọi đến phương pháp:

methodMain.Statements.Add(new CodeExpressionStatement(
       new CodeMethodInvokeExpression(
         new CodeMethodReferenceExpression(
         new CodeVariableReferenceExpression("dict"), 
          "Print", 
           new CodeTypeReference[] { 
            new CodeTypeReference("System.Decimal"), 
             new CodeTypeReference("System.Int32"),}), 
              new CodeExpression[0]))); 

(Bạn sẽ sử dụng CodeThisReferenceExpression() hoặc CodeBaseReferenceExpression() thay cho CodeVariableReferenceExpression), n ot chắc chắn nếu đó là những gì bạn có nghĩa là bằng cách gọi phương thức lớp cơ sở tiêu chuẩn.

Các vấn đề liên quan