【发布时间】:2018-09-05 03:29:16
【问题描述】:
查看以下说明我的 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 方法中创建断点并想查看 foo 的 Key 属性时,Visual Studio 不会为我提供工具提示。
通过将foo.Key 添加到监视窗口,我收到以下错误:
错误 CS1061:“T”不包含“Key”的定义,并且没有 接受“T”类型的第一个参数的扩展方法“Key”可以是 找到(您是否缺少 using 指令或程序集引用?)
当我将通用声明更改为 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 添加到监视窗口或将?foo.Key 写入即时窗口会带来上述错误,并且当您将鼠标悬停在Key 的foo.Key 上时,您不会得到工具提示
使用 Visual Studio 2015、2017 测试。
【问题讨论】:
-
你可以在观察窗口内cast到
Foo。应该有帮助。 -
也许不要依赖隐含的
T定义,尝试使用:PrintFoo<Foo>(new Foo() { Key = "Hello World" }); -
那说它看起来像 VS 中的一个错误。最好的做法是report it to Microsoft。
-
我要问一个愚蠢的问题:与
private static void PrintFoo(IFoo foo)相比,使用private static void PrintFoo<T>(T foo) where T : IFoo有什么优势? -
@Richardissimo 在这种情况下没有,但此代码仅用于演示问题。
标签: c# visual-studio