()=>构造

fer*_*ith 4 visual-studio-2005 oauth visual-studio-2008 c#-3.0 c#-2.0

我正在将一个项目从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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ServiceLocator.SetLocatorProvider(()=> injector);

我能理解这是什么吗?

tan*_*ius 10

这是一个lambda表达式.

我猜这个SetLocatorProvider方法有一个签名,如:

SetLocatorProvider( Func<IServiceLocator> callback ):
Run Code Online (Sandbox Code Playgroud)

现在你必须提供这样的回调.基本上有三种选择:

使用方法(始终工作):

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

ServiceLocator.SetLocatorProvider( GetServiceLocator() );
Run Code Online (Sandbox Code Playgroud)

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

ServiceLocator.SetLocatorProvider( delegate
        {
            // return IServiceLocator
        } );
Run Code Online (Sandbox Code Playgroud)

使用lambda(需要C#3.0):
这是你看到的代码......
由于没有参数(Func<IServiceLocator>只有返回值),你可以使用以下命令来指定():

ServiceLocator.SetLocatorProvider( () => { /* return IServiceLocator */ } );
Run Code Online (Sandbox Code Playgroud)

这可以翻译成

ServiceLocator.SetLocatorProvider( () => /* IServiceLocator */ );
Run Code Online (Sandbox Code Playgroud)

也许你也想读这个问题+答案.