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)
如果编译器在上下文的理解是,Foo在new Foo一类,为什么就不能明白Foo的nameof(Foo.Bar)是也是一类?如果Foo是一种方法,这种表示法毫无意义.
在第一种情况下,由于new关键字,编译器知道您的意思是类.接下来new 有是一个类型的名字.
在第二种情况下,没有这样的限制:Foo可以是任何变量,成员,字段或类型.(注意,如果这应该可以工作,则Bar需要是static类的属性Foo).
但由于该方法Foo位于最接近的范围内,编译器认为您的意思是此方法组,该组没有成员调用Bar.
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |