How to define an extension method in a scriptcs csx script

不问归期 提交于 2019-11-30 17:29:47

I feel your pain.

Actually this is a limitation of Roslyn currently as it wraps everything into a class even if it is another class.

I've talked to the Roslyn team however and they are going to support extension methods soon.

Unfortunately, because compiling something on the fly requires a class, scriptcs was designed to take the raw code that mattered and wrap it in a class. You would need to modify a version of scriptcs for your needs -or consider contributing to the project.

However, I too love scriptcs and think it's one of the most fantastic projects out there today!

I too tried this early on when using scriptcs and my heart broke when it didn't work. If I had more bandwidth I'd contribute this addition on my own.

AFAIK this is not a limitation with Roslyn.

Good news! It is now supported in C# script files (.csx)

But you have to declare an extension method on top level:

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

Do not declare it in a static class:

// this will not work!
public static class MyExtensionsClass
{
    static string MyToLowerExtension(this string str)
    {
        return str.ToLower();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!