当存在接口和实现时,Var关键字类型推断歧义

Man*_*ank 5 c#

举个例子:

interface IEntity {
    string Name { get; set; }
}

class Product : IEntity {
    public string Name { get; set; }
    public int Count { get; set; } // added member
}

class Client {
    void Process() {
        var product = new Product();
        int count = product.Count; // this is valid            

    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,什么是产品类型?是IEntity还是产品?看来产品是具体实施类型(产品).如果是这种情况,则不应仅在特殊情况下使用var.但我发现像resharper这样的工具建议默认使用var.不应该有一个程序到界面?

cbp*_*cbp 7

如果您仍在实例化方法中的具体类,则实际上并不是"编程到接口",因为依赖于具体的Product类仍然存在.为了正确编程到接口,必须删除新的实例化,例如使用工厂或IoC.


JP *_*oto 6

如果您有像......那样的产品怎么办?

class Product : IFirst, ISecond, IThrid
Run Code Online (Sandbox Code Playgroud)

编译器可以做的唯一合理的事情是它的作用.我不限制我的使用var,我到处使用它.我认为它使代码更具可读性.在这种情况下,我同意ReSharper的全面意见.


iro*_*sam 1

var product = new Product()属于 类型Product。如果您没有使用该接口之外的成员(Product.Count不在接口上IEntity),则可以对该接口进行编程。

添加:

另外,在 VS2008 中,您可以将鼠标悬停var在声明中的关键字上以查看隐含类型。此悬停/工具提示消息也适用于声明行之后的变量名称。(摘自C# 深入研究,第 211 页)