2010-03-06 3 views
1

다음 코드를 사용하여 속성을 람다 식에 전달했습니다.람다 식을 인수로 받아들이는 방법을 만드는 방법은 무엇입니까?

namespace FuncTest 
{ 
    class Test 
    { 
     public string Name { get; set; } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      Test t = new Test(); 
      t.Name = "My Test"; 
      PrintPropValue(t => t.Name); 

     } 

     private static void PrintPropValue(Func<string> func) 
     { 
      Console.WriteLine(func.Invoke()); 
     } 

    } 
} 

이것은 컴파일되지 않습니다. 나는 그 기능이 재산을 가지고 평가할 수 있기를 바랄뿐입니다.

+0

컴파일 오류 란 무엇입니까? –

+0

lambda를 저글링하는 대신에'PrintPropValue (string prop)'를 해결하는 것이 어떻습니까? 인스턴스를 가져 와서 속성을 반환하는 식을 갖고 싶습니까? –

+0

@ amdras : 나는 방금 램다를 배우려고 노력하고 있습니다. – Amitabh

답변

8

Func<string>에는 매개 변수가 없지만 람다 식에서는 매개 변수가 없습니다. 당신이 테스트의 특정 인스턴스를 캡처하는 Func<string>을할지 여부 -이 경우 당신이 대리자를 호출 할 때 Test의 인스턴스를 전달해야합니다 -

그것은 당신이 정말Func<Test, string>을 할 것인지 분명하지 않다. 후자의 경우 :

using System; 

class Test 
{ 
    public string Name { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Test t = new Test(); 
     t.Name = "My Test"; 
     // Note: parameterless lambda expression 
     PrintPropValue(() => t.Name); 

     // Demonstration that the reference to t has been captured, 
     // not just the name: 

     Func<string> lambda =() => t.Name; 
     PrintPropValue(lambda); 
     t.Name = "Changed"; 
     PrintPropValue(lambda); 
    } 

    private static void PrintPropValue(Func<string> func) 
    { 
     Console.WriteLine(func.Invoke()); 
    } 
} 
2
class Program 
{ 
    static void Main(string[] args) 
    { 
     Test t = new Test(); 
     t.Name = "My Test"; 

     //Use a lambda with a free variable 
     Func<Test, string> lambda = x => x.Name; 
     PrintPropValue(t, lambda); 

     //Close the lambda over its free variable. 
     //It will refer to the t 
     //captured from the current scope from now on 
     //Note: 'lambda' is unchanged, it still can be used 
     //with any 'Test' instance. We just create a (new) 
     //closure using the 'lambda'. 
     Func<string> closure =() => lambda(t); 
     PrintPropValue(closure); 

     //This will still print 'My Test', 
     //despite the fact that t in that scope 
     //refers to another variable. 
     AnotherT(closure); 

     t.Name = "All your " + t.Name + " captured and are belong to us."; 
     //This will now print 'All your My Test captured and are belong to us.' 
     AnotherT(closure); 

    } 

    private static void AnotherT(Func<string> closure) 
    { 
     Test t = new Test(); 
     t.Name = "My Another Test"; 

     PrintPropValue(closure); 

    } 

    private static void PrintPropValue<T>(T instance, Func<T, string> func) 
    { 
     Console.WriteLine(func(instance)); 
    } 

    private static void PrintPropValue(Func<string> func) 
    { 
     Console.WriteLine(func()); 
    } 

} 
관련 문제