查看以下演示我的 Visual Studio 2017 编译器问题的内容
public interface IFoo
{
string Key { get; set; }
}
public class Foo : IFoo
{
public string Key { get; set; }
}
class Program
{
static void Main(string[] args)
{
PrintFoo(new Foo() { Key = "Hello World" });
Console.ReadLine();
}
private static void PrintFoo<T>(T foo) where T : IFoo
{
//set breakpoint here and try to look at foo.Key
Console.WriteLine(foo.Key);
}
}
当我在 PrintFoo
中设置断点时方法,想看看Key
foo
的属性(property)Visual Studio 不会为我提供工具提示。
通过添加 foo.Key
到监 window 口我收到以下错误:
error CS1061: 'T' does not contain a definition for 'Key' and no extension method 'Key' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
当我将通用声明更改为 Foo
时而不是 IFoo
编译器可以访问“Key”属性,因此:
private static void PrintFoo<T>(T foo) where T : Foo
{
//set breakpoint here and try to look at foo.Key
Console.WriteLine(foo.Key);
}
有没有办法让它发挥作用?
编辑:
同时,查看本地窗口并将鼠标悬停在 foo
上获取工具提示,而不是扩展属性。
添加foo.Key
到 watch 窗口或写?foo.Key
进入即时窗口会带来上述错误,当您将鼠标悬停在 Key
上时,您不会得到工具提示。的 foo.Key
已使用 Visual Studio 2015、2017 进行测试。
最佳答案
此问题有两种解决方法。使用工具 > 选项 > 调试 > 常规。您可以勾选“使用托管兼容模式”或“使用旧版 C# 和 VB.NET 表达式计算器”。
“使用托管兼容模式”不必要地晦涩难懂,它实际上所做的是将新的调试引擎替换为上次在 VS2010 中使用的引擎。好的。它实际上还为您提供了遗留表达式计算器。我建议您使用这个,因为它还避免了新调试引擎中的许多其他错误。这在 VS2015 中特别有问题。
我发现很少有理由将其关闭。您错过了最近添加的调试器功能,我只知道方法返回值检查、64 位代码的编辑+继续以及在非 Windows 系统上的 .NETCore 中使用的新的可移植 PDB 格式。它必须 用于调试 C++/CLI 代码。我不知道新的表达式评估器有什么更好的,从来没有注意到任何东西。没有他们,我的生活很轻松,至少对我而言。
我不太了解调试器团队的内部情况,无法真正了解发生了什么。但它看起来不太好,VS2017 添加了一些新的令人讨厌的故障模式,新的调试引擎在最糟糕的时候崩溃成一堆瓦砾。从表面上看这些选项,它们肯定存在,因为它们知道最新版本不合时宜。
更新:正如 Rand 所指出的,这个特定的缺陷似乎已经得到解决。我在版本 15.9.3 中看到了正确的行为。
关于c# - 如果声明是接口(interface),编译器无法识别泛型中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49307586/