如何定义一个scriptcs CSX脚本扩展方法脚本、定义、方法、CSX

2023-09-03 16:01:03 作者:和xx一起看月亮

我玩 ScriptCS (这是真棒!),但我无法找出如何定义扩展方法在一个.csx脚本文件。

I'm playing with ScriptCS (which is awesome!) but I couldn't figure out how to define an extension method within a .csx script file.

拿这个例子:

using System.IO;

public static class Extensions
{
    public static string Remove(this string source, params string[] toRemove)
    {
        foreach(var r in toRemove)
        {
            source = source.Replace(r,"");
        }
        return source;
    }
}

string[] entries = 
    Directory
        .GetFiles(
            @"C:\Users\blah\blah",
            "*.mp4",
            SearchOption.AllDirectories)
    .Select( p => p.Remove("Users"))
    .ToArray();

foreach(var e in entries)
{
    Console.WriteLine(e);
}

这会产生错误:

错误CS1109:扩展方法必须在顶级静态定义   类;扩展是一个嵌套类

error CS1109: Extension methods must be defined in a top level static class; Extensions is a nested class

我猜ScriptCS包装了CSX在一些班级,这是造成扩展嵌套,有没有解决这个办法吗?

I'm guessing that ScriptCS wraps the csx in some class which is causing extensions to be nested, is there any way around this?

推荐答案

我觉得你的疼痛。

其实这是罗斯林的限制目前,因为它包装一切都变成一个类,即使它是另一个类。

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.