【问题标题】:Visual Studio Compiles Successfully but Roslyn BalksVisual Studio 编译成功,但 Roslyn 拒绝
【发布时间】:2020-07-09 16:59:13
【问题描述】:

我正在编写 C# 代码分析器并遇到问题。以下源代码文件:

using System;

namespace J4JSoftware.Logging
{
    // added to test SharpDoc
    [AttributeUsage( validOn: AttributeTargets.Class | AttributeTargets.Interface, Inherited = false, AllowMultiple = true )]
    public class DummyAttribute : Attribute
    {
#pragma warning disable 67
        // ReSharper disable once EventNeverSubscribedTo.Global
        public event EventHandler<int> Ralph;
#pragma warning restore 67
        
#pragma warning disable 8618
        public DummyAttribute( string arg1, Type arg2 )
#pragma warning restore 8618
        {
        }

        public int TestField;
    }

    public interface IDummyInterface1
    {
        int Number { get; set; }
    }

    public interface IDummyInterface2 : IDummyInterface1
    {
        string Text { get; set; }
    }

    public interface IDummyInterface3<in T>
        where T : DummyAttribute
    {
        string GetValue( T item );

        bool TestGenericMethod<TMethod>()
            where TMethod : class, IDummyInterface1;
    }
}

在 Visual Studio 2019 中编译没有任何错误或警告。但它会生成 CS0116 错误 --

命名空间不能直接包含字段或方法等成员。

当我使用 Roslyn 编译它时。导致错误的引用行号是第 0 行,“using System;”。

是什么导致了这种行为,我该如何解决?

【问题讨论】:

    标签: c# roslyn roslyn-code-analysis


    【解决方案1】:

    叹息。键盘错误的白痴。我会在这里描述,以防其他人犯同样的错误。

    要编译一个项目,您必须首先解析源代码文件(并且还要做一些其他事情)。我这样调用解析器:

    var tree = CSharpSyntaxTree.ParseText( srcFile );
    

    但我应该这样称呼它:

    var tree = CSharpSyntaxTree.ParseText( File.ReadAllText(srcFile) );
    

    解析器需要源代码,而不是文件路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多