2010-07-16 31 views
4

我正在將一個項目從Visual Studio 2005轉換爲Visual Studio 2008,並且出現在上述構造中。()=>構造

using Castle.Core.Resource; 
using Castle.Windsor; 
using Castle.Windsor.Configuration.Interpreters; 
using CommonServiceLocator.WindsorAdapter; 
using Microsoft.Practices.ServiceLocation; 

namespace MyClass.Business 
{ 
    public class Global : System.Web.HttpApplication 
    { 
     public override void Init() 
     { 
      IServiceLocator injector = 
       new WindsorServiceLocator(
        new WindsorContainer(
         new XmlInterpreter(
          new ConfigResource("oauth.net.components")))); 

      //ServiceLocator.SetLocatorProvider(() => injector); 

      // ServiceLocator.SetLocatorProvider(injector); 
     } 
    } 
} 

ServiceLocator.SetLocatorProvider(()=> injector);

我可以理解這是什麼。

回答

10

這是一個lambda expression

我猜測,SetLocatorProvider方法具有類似特徵:

SetLocatorProvider(Func<IServiceLocator> callback): 

現在,你必須提供這樣的回調。基本上有三種選擇:

使用方法(總是工作):

private IServiceLocator GetServiceLocator() { /* return IServiceLocator */ } 

ServiceLocator.SetLocatorProvider(GetServiceLocator()); 

使用委託(需要C#2.0):

ServiceLocator.SetLocatorProvider(delegate 
     { 
      // return IServiceLocator 
     }); 

使用lambda(requir ES C#3.0):
這就是你看到的代碼...
由於沒有參數(Func<IServiceLocator>只有一個返回值)指定此使用()

ServiceLocator.SetLocatorProvider(() => { /* return IServiceLocator */ }); 

這可以被翻譯到

ServiceLocator.SetLocatorProvider(() => /* IServiceLocator */); 

也許你還想讀this question + answer

0

這是一個創建匿名委託的lambda表達式。也就是說,它是一個內聯的函數。參數列表在palenthesis裏面,所以在這種情況下沒有參數。當函數包含單個語句時,它隱式返回該語句的值(或者根本不返回任何內容)。

在這個特定的情況下,它是一個返回噴油器的函數。這是ServiceLocator的一種常見模式,用一個返回IoC容器的函數來初始化它。

+1

匿名代理看起來更像'new delegate(){return injector; }'。當然,在這種情況下,lamdba表達式具有創建匿名委託的效果。 – 2010-07-16 14:28:18

+0

你是對的,我很匆忙。我編輯了我的答案,以更好地闡明這一點。 – 2010-07-16 14:41:00

2

這是創建不帶參數的內聯委託的lambda表示法。

0

它不是一個構造函數,而是一個Lambda表達式。有關更多詳細信息,請參閱here

在這種情況下()意味着沒有參數=>是Lamda操作符並且正在返回噴油器。

2

這是一個lambda。如果你熟悉委託,就像聲明一個方法,該方法返回injector並將其用作委託,除了你已經將方法內聯。第一個()包含lambda的參數。例如,在事件處理中,您經常會看到(src, e),其中src是事件的發起者,而e是事件本身。這些參數隨後可供後續代碼使用。

如果是多行,則可以將(args) => { brackets }放在代表的周圍並返回值。這是速記。

+0

如何將其轉換回Visual Studio構造 – ferronrsmith 2010-07-16 14:22:28

+0

它應該在VS2008中正常工作。如果你想以舊式的方式,把lambda變成一個方法,並用它作爲代表: ServiceLocator.SetLocatorProvider(CreateInjector); – Lunivore 2010-07-16 14:25:45

+0

@ferronrsmith - lambdas的實際.Net類型是通用的'Func <>'和'Action <>'類型。泛型參數表示函數參數(以及Func <>的返回類型)。這些只是特殊的委託類,使事情更容易使用。 – 2010-07-16 14:25:53

相關問題