在C#5中无法使用自动属性进行显式接口实现,但现在C#6支持仅使用getter的自动属性,现在应该可以使用,对吧?
在C#6中创建自动属性成功,但是当尝试在构造函数中为其赋值时,必须首先this转换为接口类型,因为实现是显式的.但这就是VS 2015 RC和VS Code 0.3.0都显示错误,可以在评论中看到:
using static System.Console;
namespace ConsoleApp
{
public interface IFoo { string TestFoo { get; } }
public class Impl : IFoo
{
// This was not possible before, but now works.
string IFoo.TestFoo { get; }
public Impl(string value)
{
// ERROR: Property or indexer 'IFoo.TestFoo' cannot be assigned to -- it is read only.
((IFoo)this).TestFoo = value;
}
}
public class Program
{
// Yes, not static. DNX …Run Code Online (Sandbox Code Playgroud) 为什么在实现接口时允许更改属性中getter或setter的可见性和存在?
interface IFoo
{
string Bar { get; }
}
class RealFoo : IFoo
{
public RealFoo(string bar)
{
this.Bar = bar;
}
public string Bar { get; private set; }
}
class StubFoo : IFoo
{
public string Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
......在实现抽象类时,做同样的事情并不合法吗?
abstract class AbstractFoo : IFoo
{
public abstract string Bar { get; }
}
class RealFoo : AbstractFoo
{
public RealFoo(string bar)
{
this.Bar = bar;
}
// Cannot override because 'Bar' does not …Run Code Online (Sandbox Code Playgroud)