Tag: language design

为什么接口实现不能返回更具体的类型?

如果接口指定了返回另一个接口的属性或方法,为什么第一个接口的实现不允许将返回类型“更改”为更具体的类型? 我们举一个例子来说明: interface IFoo { IBar GetBar(); } interface IBar { } class Foo : IFoo { // This is illegal, we are not implementing IFoo properly public Bar GetBar() { return new Bar(); } } class Bar : IBar { } 我知道如何让它发挥作用,这不是我关心的问题。 我可以: 将GetFoo()返回类型更改为IBar ,或 显式实现接口,只需从IFoo.GetBar()方法调用GetBar 我真正要问的是不仅允许上面的代码编译的原因。 有没有上述情况不符合IFoo规定的合同。

Visual Basic关键字的C#等价物:’With’…’End With’?

在Visual Basic中,如果要更改单个对象的多个属性,则有一个With/End With语句: Dim myObject as Object // ‘ Rather than writing: myObject.property1 = something myObject.property2 = something2 // ‘ You can write: with myObject .property1 = something .property2 = something2 … End With 我知道C#可以在创建新对象时执行此操作: Object myObject = new Object { property1 = something, property2 = something2, …}; 但是如果已经创建了myOject我该怎么做呢(就像Visual Basic正在做的那样)?