首页 \ 问答 \ 在Roslyn VB.NET中缺少我的命名空间(Missing My namespace in Roslyn VB.NET)

在Roslyn VB.NET中缺少我的命名空间(Missing My namespace in Roslyn VB.NET)

当我尝试使用Roslyn编译并发出以下VB.NET代码时,

Module Module1
    Sub Main()

        Console.WriteLine(My.Application.Info.AssemblyName)

    End Sub
End Module

我收到以下错误

error BC30451: 'My' is not declared. It may be inaccessible due to its protection level.

MSDN 提到我的命名空间是由编译器根据_MYTYPE条件编译常量的值添加的。

在Roslyn,我的魔法不再可用了,是吗?

我的代码:

Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.VisualBasic.CompilerServices

Module Module1
    Sub Main()

        Dim code = "Module Module1" + Environment.NewLine +
                       "Sub Main()" + Environment.NewLine +
                           "System.Console.WriteLine(My.Application.Info.AssemblyName)" + Environment.NewLine +
                       "End Sub" + Environment.NewLine +
                   "End Module"

        Dim tree = VisualBasicSyntaxTree.ParseText(code)

        Dim compilation = VisualBasicCompilation.Create("test").
            AddSyntaxTrees(tree).
            AddReferences(MetadataReference.CreateFromFile(GetType(Object).Assembly.Location)).
            AddReferences(MetadataReference.CreateFromFile(GetType(StandardModuleAttribute).Assembly.Location))

        Dim emitResult = compilation.Emit("test.exe")
        If Not emitResult.Success Then
            Console.Write(String.Join(Environment.NewLine, emitResult.Diagnostics))
        End If

        Console.ReadLine()

    End Sub
End Module

When I try to compile and emit the following VB.NET code using Roslyn,

Module Module1
    Sub Main()

        Console.WriteLine(My.Application.Info.AssemblyName)

    End Sub
End Module

I get the following error

error BC30451: 'My' is not declared. It may be inaccessible due to its protection level.

MSDN mentions that My namespace is added by the compiler depending on value of the _MYTYPE conditional-compilation constant.

In Roslyn all that My magic is not available anymore, is it?

My code:

Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.VisualBasic.CompilerServices

Module Module1
    Sub Main()

        Dim code = "Module Module1" + Environment.NewLine +
                       "Sub Main()" + Environment.NewLine +
                           "System.Console.WriteLine(My.Application.Info.AssemblyName)" + Environment.NewLine +
                       "End Sub" + Environment.NewLine +
                   "End Module"

        Dim tree = VisualBasicSyntaxTree.ParseText(code)

        Dim compilation = VisualBasicCompilation.Create("test").
            AddSyntaxTrees(tree).
            AddReferences(MetadataReference.CreateFromFile(GetType(Object).Assembly.Location)).
            AddReferences(MetadataReference.CreateFromFile(GetType(StandardModuleAttribute).Assembly.Location))

        Dim emitResult = compilation.Emit("test.exe")
        If Not emitResult.Success Then
            Console.Write(String.Join(Environment.NewLine, emitResult.Diagnostics))
        End If

        Console.ReadLine()

    End Sub
End Module
更新时间:2022-04-24 09:04

最满意答案

如果我理解正确的是什么,则通过自动将文件VbMyTemplateText.vb到每个编译中来添加My命名空间。 为了使它实际生成一些东西,必须正确设置预处理器符号_MYTYPE (在控制台应用程序的情况下为"Console" )。

要使这项工作,你还需要引用System.dll ,但之后一切正常:

Imports System.CodeDom.Compiler
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.VisualBasic.CompilerServices

Module Module1

    Sub Main()
        Dim code = "Module Module1" + Environment.NewLine +
                       "Sub Main()" + Environment.NewLine +
                            "System.Console.WriteLine(My.Application.Info.AssemblyName)" + Environment.NewLine +
                       "End Sub" + Environment.NewLine +
                   "End Module"

        Dim tree = VisualBasicSyntaxTree.ParseText(code)

        Dim compilation = VisualBasicCompilation.Create("test").
            AddSyntaxTrees(tree).
            AddReferences(MetadataReference.CreateFromFile(GetType(Object).Assembly.Location)). ' mscorlib
            AddReferences(MetadataReference.CreateFromFile(GetType(GeneratedCodeAttribute).Assembly.Location)). ' System
            AddReferences(MetadataReference.CreateFromFile(GetType(StandardModuleAttribute).Assembly.Location)). ' Microsoft.VisualBasic
            WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithParseOptions(
                VisualBasicParseOptions.Default.WithPreprocessorSymbols(New KeyValuePair(Of String, Object)("_MYTYPE", "Console"))))

        Dim emitResult = compilation.Emit("test.exe")
        If Not emitResult.Success Then
            Console.WriteLine(String.Join(Environment.NewLine, emitResult.Diagnostics))
        End If

    End Sub

End Module

If I understand what's going on correctly, the My namespace is added by automatically including the file VbMyTemplateText.vb into each compilation. And to make it actually generate something, the preprocessor symbol _MYTYPE has to be set correctly (in the case of a console application to "Console").

To make this work, you also need to reference System.dll, but after that everything works fine:

Imports System.CodeDom.Compiler
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.VisualBasic.CompilerServices

Module Module1

    Sub Main()
        Dim code = "Module Module1" + Environment.NewLine +
                       "Sub Main()" + Environment.NewLine +
                            "System.Console.WriteLine(My.Application.Info.AssemblyName)" + Environment.NewLine +
                       "End Sub" + Environment.NewLine +
                   "End Module"

        Dim tree = VisualBasicSyntaxTree.ParseText(code)

        Dim compilation = VisualBasicCompilation.Create("test").
            AddSyntaxTrees(tree).
            AddReferences(MetadataReference.CreateFromFile(GetType(Object).Assembly.Location)). ' mscorlib
            AddReferences(MetadataReference.CreateFromFile(GetType(GeneratedCodeAttribute).Assembly.Location)). ' System
            AddReferences(MetadataReference.CreateFromFile(GetType(StandardModuleAttribute).Assembly.Location)). ' Microsoft.VisualBasic
            WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithParseOptions(
                VisualBasicParseOptions.Default.WithPreprocessorSymbols(New KeyValuePair(Of String, Object)("_MYTYPE", "Console"))))

        Dim emitResult = compilation.Emit("test.exe")
        If Not emitResult.Success Then
            Console.WriteLine(String.Join(Environment.NewLine, emitResult.Diagnostics))
        End If

    End Sub

End Module

相关问答

更多
  • 你做错了。 首先,您需要将引用添加到适当的编译器程序集中。 Roslyn.Compilers.dll Roslyn.Compilers.CSharp.dll 添加任何您想要的线条。 using Roslyn.Scripting.CSharp; 然后创建引擎,您的会话并运行您的代码。 var engine = new ScriptEngine(); var session = engine.CreateSession(); session.Execute("using System;"); session. ...
  • 我刚刚面对同样的问题。 当您创建一个新的Web项目时,两个nuget包将自动添加到您的项目中。 如果你删除它们,你的问题应该解决。 软件包名称为:“ Microsoft.CodeDom.Providers.DotNetCompilerPlatform ”和“ Microsoft.Net.Compilers ”。 I've just faced the same problem. When you create a new web project, two nuget packages automatical ...
  • 默认命名空间是MSBuild和Visual Studio的属性,而不是编译器本身。 因此,您不会在Roslyn API中找到它。 相反,您可以直接在项目文件中更改元素。 您可以在此处查看Roslyn的Visual Studio图层如何获取默认命名空间。 The default namespace is a property of MSBuild and Visual Studio, not the compilers themselves. Therefore, you won ...
  • 问题是System.Collections.Immutable版本,我使用的是1.5.0-预览,因为我点击了nuget包管理器UI中的更新。 尽快将System.Collections.Immutable降级到版本1.3.1,异常消失了。 The problem was System.Collect ...
  • 从我可以收集的名字空间现在已经过时了。 如果有人感兴趣, SyntaxFactory替换Syntax 。 From what I can gather the namespaces are obsolete now. SyntaxFactory replaces Syntax if anyone is interested.
  • 我在VS 2015中创建了一个新的MVC应用程序,并盯着它安装的NuGet包。 事实证明,我们显然需要安装 Microsoft.Net.Compilers NuGet包 (而不是Microsoft.CodeDom.Providers.DotNetCompilerPlatform包)。 编辑:经过这个解决方案的更多摆弄后,它似乎并不比我在OP中提供的(失败的)解决方案更好。 但不要害怕,显然有一个答案(如果你正在运行VS 2015)。 我会将其作为一个单独的答案发布。 Per this MSDN blog p ...
  • 类型安全是一个静态的东西,强制执行编译时(应用程序)。 创建和运行CSharpScript是在运行时完成的。 因此,您无法在运行时强制执行类型安全性。 也许CSharpScript不是正确的方法。 通过使用这个SO答案, 您可以将一段C#代码编译到内存中并使用Roslyn生成汇编字节。 然后你会改变这条线 object obj = Activator.CreateInstance(type); 至 IScript obj = Activator.CreateInstance(type) a ...
  • 如果我理解正确的是什么,则通过自动将文件VbMyTemplateText.vb到每个编译中来添加My命名空间。 为了使它实际生成一些东西,必须正确设置预处理器符号_MYTYPE (在控制台应用程序的情况下为"Console" )。 要使这项工作,你还需要引用System.dll ,但之后一切正常: Imports System.CodeDom.Compiler Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic ...
  • 您可以通过.csproj AdditionalFiles项添加分析器运行时配置。 它们扩展到/additionalfile:编译器的/additionalfile:命令行选项。 在VS“15”预览中,您可以从UI执行此操作: 设置此项会将以下内容添加到.csproj中: 您的Analyzer可以通过CompilationStartAnalysisCon ...
  • 旧编译器只是不允许它(因为该语言是基于行的),并且当实现Roslyn扫描器和解析器时,我们添加了支持以继续扫描换行符作为字符串文字的一部分。 The old compiler just didn't allow it (because the language was line based), and when the Roslyn scanner and parser were implemented, we added support to continue scanning through newli ...

相关文章

更多

最新问答

更多
  • 在csproj中使用appdata环境变量(Use appdata environment variable in csproj)
  • 从背景返回后,Skobbler Map崩溃(Skobbler Map crashes after returning from background)
  • 如何保持对绑定服务的轮询?(How to keep polling a bound service?)
  • ASP.NET单选按钮jQuery处理(ASP.NET radio button jQuery handling)
  • Linux上的FORTRAN图形库(FORTRAN graphic library on Linux)
  • 我们如何根据索引更新dynamodb表(不基于primary has和range key)(how can we update dynamodb table based on index(not based on primary has and range key))
  • 功能包装避免重复(wrap of functions avoid duplicating)
  • Android BroadcastReceiver和Activity.onPause()(Android BroadcastReceiver and Activity.onPause())
  • 无法使用phonegap 2.4在Android上播放录音(unable to play audio recordings on android using phonegap 2.4)
  • VS2015 + Resharper:不要使用C#6(VS2015 + Resharper: Don't use C#6)
  • 大学电脑四级对初学者来说要多久能过
  • 特殊字符删除?(Special characters remove?)
  • Android视频教程现在网上的都比较零散呢?有些太坑爹了,感觉老师就是在想当然的讲
  • 计算同一个表中不同行之间的差异[重复](Calculate delta's between different rows in same table [duplicate])
  • Javaweb开发,技术路线是什么?该怎么写?
  • JavaScript只在php代码中执行一次(JavaScript only executes once inside php code)
  • 不兼容的字符编码:ASCII-8BIT和UTF-8(incompatible character encodings: ASCII-8BIT and UTF-8)
  • Clojure(加载文件)给出错误(Clojure (load-file) gives an error)
  • 为具有瞬态scala依赖性的spring-xd项目优化gradle(Optimize gradle for spring-xd project with transient scala dependency)
  • 如何才能在Alpha测试模式下发布我的应用程序?(How can I publish my app in Alpha test mode only?)
  • “没有为此目标安装系统映像”Xamarin AVD Manager(“No system images installed for this target” Xamarin AVD Manager)
  • maven中的Scalatest:JUnit结果(Scalatest in maven: JUnit results)
  • 使用android SDK将文件直接上传到存储桶中的文件夹(Upload a file directly to a folder in bucket using android SDK)
  • 是否应将plists导入CoreData?(Should plists be imported to CoreData?)
  • java.lang.reflect.InvocationTargetException JavaFX TableView(java.lang.reflect.InvocationTargetException JavaFX TableView)
  • 根据唯一列值动态创建多个子集(Dynamically create multiple subsets based on unique column values)
  • 使用CSS可以使HTML锚标签不可点击/可链接吗?(Is it possible to make an HTML anchor tag not clickable/linkable using CSS?)
  • 嵌套的模板可能性(Nested template possibilities)
  • 任何方式在iOS7 +上以编程方式打开蓝牙(Any way to turn on bluetooth programmatically on iOS7+)
  • 如何为给定的SQL查询编写JPA查询(How I can write JPA query for given SQL query)