为什么编译器找不到合适的类型?

Fre*_*ios 3 c# compiler-errors roslyn ambiguous-grammar

我有一个方法和一个同名的类.在一种情况下,编译器知道我使用的是类名,但在另一种情况下则不然:

using System;
using DTO;

namespace DTO
{
    public class Foo
    {
        public string Bar { get; set; }
    }
}

namespace Tests
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }


        private void Foo()
        {
            var foo = new Foo // Ok
            {
                Bar = nameof(Foo.Bar) // Not ok
            };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

错误:

CS0119 'Program.Foo()' is a method, which is not valid in the given context
Run Code Online (Sandbox Code Playgroud)

我得到一个静态属性相同的错误:

public class Foo
{
    public static string Bar = "Hello";
}

// ...

private void Foo()
{
    var bar = Foo.Bar; // Error
}
Run Code Online (Sandbox Code Playgroud)

如果编译器在上下文的理解是,Foonew Foo一类,为什么就不能明白Foonameof(Foo.Bar)是也是一类?如果Foo是一种方法,这种表示法毫无意义.

Ren*_*ogt 7

在第一种情况下,由于new关键字,编译器知道您的意思是类.接下来new 是一个类型的名字.

在第二种情况下,没有这样的限制:Foo可以是任何变量,成员,字段或类型.(注意,如果这应该可以工作,则Bar需要是static类的属性Foo).

但由于该方法Foo位于最接近的范围内,编译器认为您的意思是此方法组,该组没有成员调用Bar.

  • 现在,当然,编译人员可以为此编写复杂的启发式方法,说"好吧,它可能不是(方法).Bar,因为这看起来很奇怪,我们可以发现有一个名为Foo的类型,所以我们将使用它而不是使代码编译",他们没有这样做的第一个也是最重要的原因是他们没有这样做. (2认同)