使用仅限getter的自动属性(C#6功能)显式实现接口

Nik*_*ird 21 c# c#-6.0

在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 supports that (for constructor DI).
        public void Main(string[] args)
        {
            IFoo foo = new Impl("World");

            WriteLine($"Hello {foo.TestFoo}");
            ReadKey(true);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:我更新了设置常量值的原始问题TestFoo.在我的真实场景中,值来自注入构造函数的对象.如果属性返回的值可以在初始化时设置,那么Daniel A. White答案非常好.

它说:

属性或索引器'IFoo.TestFoo'无法分配 - 它是只读的.

有没有办法解决这个问题,或者我仍然需要在这种情况下使用支持字段的属性?

我使用Visual Studio 2015 RC和Visual Studio Code 0.3.0与DNX451 1.0.0-beta4.

在Roslyn GitHub页面上提出了一个问题.


可能重复的是关于一个接口的具有可读取正规属性的定义问题.我的问题是关于使用新的C#6功能明确地实现这样的接口,理论上应该使这成为可能.请参阅我在第一句中为类似问题链接的另一个问题(但对于C#5,其中仅限getter的自动属性尚未提供).

Ale*_*ese 4

您可以通过为显式实现的属性使用只读支持字段来解决此问题。您可以将注入的值分配给构造函数中的支持字段,显式属性的 get 实现将返回它。

public class Impl : IFoo
{
    private readonly string _testFoo;

    string IFoo.TestFoo => _testFoo;

    public Impl(string value)
    {
        _testFoo = value;
    }
}
Run Code Online (Sandbox Code Playgroud)