且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在没有嵌套类的情况下,如何在Azure Functions***享扩展方法?

更新时间:2022-11-03 21:17:20

为了正确地包括Azure Function的扩展方法,您可以像在所有其他情况下一样使用#load,唯一的区别在于扩展方法需要的要求成为***类是使它们成为***方法:).当Azure函数获取csx文件的编译内容被包装在一个自动创建的类中时,这就是为什么它抱怨以常规c#方式编写的扩展方法将嵌套在该自动创建的类中的原因.

In order to correctly include extension methods for Azure Function you can use a #load as in all other cases, the only difference regarding the requirement that the extension methods needs to be in a top level class is to make them a top level methods :). When Azure Function gets compiled contents of csx files are being wrapped in a auto-created class, that's why it complains that extension methods written in a regular c# way will be nested inside of that auto-created class.

了解这一点后,有一个简单的技巧就可以在单独的csx文件中具有扩展方法,并且仍在***类中对其进行定义:

When that is understood there is a simple trick to have extension methods in separate csx file and still have them defined in top-level class:

这是run.csx文件

here's run.csx file

#load "extensions.csx"

public static void Run(TimerInfo timer, TraceWriter log)
{
    log.Info("test".MyToUpperExtension());
}

和extensions.csx

and extensions.csx

static string MyToUpperExtension(this string str)
{
    return str.ToUpper();
}

static string MyToLowerExtension(this string str)
{
    return str.ToLower();
}

如您所见,常规扩展方法之间的唯一区别是您不需要自己将它们包装在静态类中.

As you see the only difference between regular extension methods is that you don't need to wrap them in a static class by yourself.