c# - Roslyn 脚本 - 使用别名

标签 c# scripting roslyn

我刚刚开始使用 Roslyn 脚本,在理解 Imports 的原理时遇到了一些困难。属性 ScriptOptions类作品。我对导入整个命名空间的概念很满意,但如果我将单个类名添加到导入列表中,则在没有完全限定它们的情况下,我无法在脚本中使用它们。例如:

错误:“CS0103:当前上下文中不存在名称“DateTime””

var scriptOptions = ScriptOptions.Default
                                 .WithReferences(typeof(DateTime).Assembly)
                                 .WithImports(typeof(DateTime).FullName);

var script = CSharpScript.Create<DateTime>("DateTime.UtcNow",
                                           scriptOptions);

var now = script.RunAsync(null, CancellationToken.None).Result;

成功:使用完全限定的类型名称

var scriptOptions = ScriptOptions.Default
                                 .WithReferences(typeof(DateTime).Assembly)
                                 .WithImports(typeof(DateTime).FullName);

var script = CSharpScript.Create<DateTime>("System.DateTime.UtcNow",
                                           scriptOptions);

var now = script.RunAsync(null, CancellationToken.None).Result;

成功:导入系统命名空间

var scriptOptions = ScriptOptions.Default
                                 .WithReferences(typeof(DateTime).Assembly)
                                 .WithImports("System");

var script = CSharpScript.Create<DateTime>("DateTime.UtcNow",
                                           scriptOptions);

var now = script.RunAsync(null, CancellationToken.None).Result;

我想做的是限制脚本,使其只能访问命名空间中的几种类型(即我不想使整个 System 命名空间可用,但允许访问System.DateTimeSystem.Math 等),但不要求脚本在使用这些类型名称时完全限定它们。我很感激,也可以添加 using对脚本本身的语句,但我理想地希望脚本引擎为我处理这个问题。

我尝试在 WithImports 中声明别名方法(例如 ScriptOptions.Default.WithImports("DateTime = System.DateTime") ),但这只会给我一个编译错误( CS0246: The type or namespace name 'DateTime = System' could not be found (are you missing a using directive or an assembly reference?) )。

文档似乎非常薄弱,但是 source for the ScriptImports class似乎表明命名空间、静态类和别名都可以导入。我是在做一些愚蠢的事情还是错过了任何明显的事情?

更新

感谢Enfyve的有用评论,我现在可以访问静态属性和方法,但在调用构造函数时仍然必须使用完全限定的名称:

var scriptOptions = ScriptOptions.Default
                                 .WithReferences(typeof(System.DateTime).FullName)
                                 .WithImports("System.DateTime");

var script = CSharpScript.Create<object>("new DateTime()", scriptOptions);

// Still throws CS0246 compiler error...
var result = script.RunAsync(null, CancellationToken.None).Result.Dump();

最佳答案

您可以通过导入类型来访问该类型的静态属性和方法,就像它是一个别名。例如:使用 .WithImports("System.DateTime") 然后使用 "UtcNow"

但是,这不是真正的类型别名指令(请参阅: Issue #7451 ) 所以你不能用这种方式创建对象。

关于c# - Roslyn 脚本 - 使用别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41951938/

相关文章:

c# - 在 C# 控制台应用程序中使用 async 和 await 异步处理文件列表

c# - 创建办公文档的缩略图

可以使用 Netbeans + PHPUnit 在远程服务器上进行 PHP 单元测试吗?

Bash 脚本用户输入提示

scripting - 期望-根据行和列从屏幕区域获取变量

c# - 我可以在带有 .NET 4.7 的 Visual Studio 2017 中使用 "Roslyn"吗?

c# - Windows 应用程序中不同大小的磁贴

c# - 用其他数据结构替换二维数组

c# - 在解决方案中使用 Roslyn 检索所有类型

metaprogramming - 使用 Roslyn,如果我有一个 IdentifierNameSyntax,我可以找到它引用的成员类型(字段、属性、方法...)