2009-10-31 31 views
1

源是引發錯誤:有什麼不對我的執行:C#擴展方法

'nn.asdf' does not contain a definition for 'extension_testmethod' 

和我真的不unterstand爲什麼...

using System.Linq; 
using System.Text; 
using System; 

namespace nn 
{ 
    public class asdf 
    { 
     public void testmethod() 
     { 
     } 
    } 
} 
namespace nn_extension 
{ 
    using nn; 
    //Extension methods must be defined in a static class 
    public static class asdf_extension 
    { 
     // This is the extension method. 
     public static void extension_testmethod(this asdf str) 
     { 
     } 
    } 
} 
namespace Extension_Methods_Simple 
{ 
    //Import the extension method namespace. 
    using nn; 
    using nn_extension; 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      asdf.extension_testmethod(); 
     } 
    } 
} 

什麼想法?

回答

6

擴展方法是被擴展其行爲像的類型的實例方法的靜態方法,也就是,可以調用它asdf類型的對象的實例。您不能將其稱爲擴展型類型的靜態方法。

更改Main到:

asdf a = new asdf(); 
a.extension_testmethod(); 

當然,你可以隨時撥打像簡單,static,非擴展方法聲明類型(asdf_extension):

asdf_extension.extension_testmethod(null); 
1

擴展方法適用於類實例:

var instance = new asdf(); 
instance.extension_testmethod();