2009-07-09 23 views
3

有什麼方法可以用lambda函數重寫一個類方法嗎?可以使用lambda函數重寫一個方法

例如與

class MyClass { 
    public virtual void MyMethod(int x) { 
     throw new NotImplementedException(); 
    } 
} 

類定義反正有做:

MyClass myObj = new MyClass(); 
myObj.MyMethod = (x) => { Console.WriteLine(x); }; 

回答

5

不可以。但是,如果您首先將方法聲明爲lambda,則可以對其進行設置,儘管我會在初始化時嘗試這樣做。

class MyClass { 
    public MyClass(Action<int> myMethod) 
    { 
     this.MyMethod = myMethod ?? x => { }; 
    } 

    public readonly Action<int> MyMethod; 
} 

但是,這不能實現聲明瞭MyMethod的接口,除非接口指定了lambda屬性。

F#有對象表達式,它允許您從lambdas中編寫對象。我希望在某些時候這是c#的一部分。

0

號方法不能像變量使用。

如果你使用JavaScript,那麼是的,你可以這樣做。

6

克里斯是正確的,方法不能像變量一樣使用。但是,你可以做這樣的事情:

class MyClass { 
    public Action<int> MyAction = x => { throw new NotImplementedException() }; 
} 

要允許被覆蓋的操作:如果您在此定義MyClass的

MyClass myObj = new MyClass(); 
myObj.TheAction = x => Console.WriteLine(x); 
myObj.DoAction(3); 

MyClass myObj = new MyClass(); 
myObj.MyAction = (x) => { Console.WriteLine(x); }; 
0

你可以這樣寫代碼方式:

class MyClass 
{ 
    public Action<int> TheAction {get;set;} 

    public void DoAction(int x) 
    { 
    if (TheAction != null) 
    { 
     TheAction(x); 
    } 
    } 
} 

卜這不應該太令人驚訝。

0

不是直接的,但有一點代碼是可行的。

public class MyBase 
{ 
    public virtual int Convert(string s) 
    { 
     return System.Convert.ToInt32(s); 
    } 
} 

public class Derived : MyBase 
{ 
    public Func<string, int> ConvertFunc { get; set; } 

    public override int Convert(string s) 
    { 
     if (ConvertFunc != null) 
      return ConvertFunc(s); 

     return base.Convert(s); 
    } 
} 

那麼你可以有代碼

Derived d = new Derived(); 
int resultBase = d.Convert("1234"); 
d.ConvertFunc = (o) => { return -1 * Convert.ToInt32(o); }; 
int resultCustom = d.Convert("1234"); 
+0

我真的沒有ConvertFunc作爲公共屬性。以上代碼僅供參考。 – 2009-07-09 01:15:51

0

取決於你想做的事,有很多方法來解決這個問題。

一個很好的起點是創建一個可以獲取和設置的委託(例如Action)屬性。然後,您可以擁有一個委託給該操作屬性的方法,或者直接在客戶端代碼中直接調用它。這開闢了許多其他選擇,例如使動作屬性可私人設定(可能提供設定它的構造器)等。

例如,

class Program 
{ 
    static void Main(string[] args) 
    { 
     Foo myfoo = new Foo(); 
     myfoo.MethodCall(); 

     myfoo.DelegateAction =() => Console.WriteLine("Do something."); 
     myfoo.MethodCall(); 
     myfoo.DelegateAction(); 
    } 
} 

public class Foo 
{ 
    public void MethodCall() 
    { 
     if (this.DelegateAction != null) 
     { 
      this.DelegateAction(); 
     } 
    } 

    public Action DelegateAction { get; set; } 
} 
相關問題