2009-07-09 8 views
3

람다 함수로 클래스 메서드를 재정의 할 수있는 방법이 있습니까?메서드를 람다 함수로 재정의 할 수 있습니까?

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

의 클래스 정의와 예를 들어

는 할 어쨌든 거기 :

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

답변

5

아니요. 그러나 처음에 람다로 메서드를 선언하면 초기화 할 때 메서드를 설정할 수 있지만 설정할 수는 있습니다. 인터페이스가 람다 속성을 지정하지 않는 이것은 그러나 MyMethod라는이있는 인터페이스를 구현할 수 없습니다

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

    public readonly Action<int> MyMethod; 
} 

, 선언했다.

F #에는 개체 표현식이있어서 람다에서 개체를 작성할 수 있습니다. 나는 이것이 C#의 일부가되기를 희망한다.

0

번호 방법은 변수처럼 사용할 수 없습니다.

JavaScript를 사용하고 있다면 가능합니다.

6

Chris가 변수와 같이 사용할 수없는 것이 맞습니다. 그러나 당신이 뭔가를 할 수 있습니다 : 당신이에 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> MyAction = x => { throw new NotImplementedException() }; 
} 

는 액션 오버라이드 (override) 할 수 있도록하려면 방법 :

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

나는 public 속성으로 ConvertFunc를 갖고 있지 않습니다. 위 코드는 실례입니다. –

0

을 가질 수있다,이 문제를 해결하는 방법에는 여러 가지가 있습니다.

좋은 시작점은 gettable 및 settable 인 대리자 (예 : Action) 속성을 만드는 것입니다. 그런 다음 해당 액션 속성에 위임하거나 단순히 클라이언트 코드에서 직접 호출하는 메서드를 가질 수 있습니다. 이것은 액션 속성을 private settable (아마도 그것을 설정하는 생성자를 제공하는 것)으로 만드는 것과 같은 다른 많은 옵션을 열어줍니다.

예.

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; } 
} 
관련 문제