我有一个同名的方法和一个类。在一种情况下,编译器知道我正在使用类名,但在另一种情况下则不然:
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
};
}
}
}
错误:
CS0119 'Program.Foo()' is a method, which is not valid in the given context
我得到与静态属性相同的错误:
public class Foo
{
public static string Bar = "Hello";
}
// ...
private void Foo()
{
var bar = Foo.Bar; // Error
}
如果编译器在上下文中理解Foo
innew Foo
是一个类,为什么它不能理解Foo
innameof(Foo.Bar)
也是一个类?Foo
如果是一种方法,则此表示法毫无意义。