开发者

What is the difference between IFoo foo = new Foo() and Foo foo = new Foo()

public class Foo : I开发者_Python百科Foo
...

What is the difference between

IFoo foo = new Foo();

and

Foo foo = new Foo();


The difference is just in the declared type of the variable. That type will then be used by the compiler whenever you use the expression foo. For example, suppose the Foo class contains some method which isn't in IFoo. With the first declaration, that member won't be visible - you'd have to cast foo to type Foo to call it. In the second declaration, you'd have direct access to it.

The reverse is true for members of IFoo which are implemented with explicit interface implementation in Foo. This is relatively rare, but it does happen.

With the first declaration, you could also reassign the variable to a reference to any other object of a type implementing IFoo, e.g.

foo = new SomeOtherIFooImplementation();

whereas with the second declaration you can only assign values which are compatible with Foo - that is, instances of Foo or a derived class. (In both cases you could set the variable to be null, of course.)

Often it's advantageous to code to an interface rather than a particular implementation. It means the compiler will prevent you from using details which are specific to the implementation, which in turn means it's likely to be easier to change to a different implementation in the future.

The type of the variable also affects things like overload resolution:

DoSomething(foo);

may call different methods depending on whether foo is declared as Foo or IFoo.

Basically the compile-time type of a variable is important in all kinds of ways - virtually every time you use the variable, some aspect of the meaning of that code will depend on the type of the variable.


If foo is of type IFoo, and Foo implemented methods or properties that are not defined in IFoo, you wouldn't be able to access them unless you cast foo to Foo.

If foo is of type IFoo, you could instantiate other types that also inhert from IFoo and assign it to foo. It's more abstracted, so you are not depending specifically on type Foo.


The first example is an instance of some object implementing IFoo. The second example is an instance of a Foo object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜