Csharp/C#教程:使用仅限getter的自动属性(C#6function)显式实现接口分享


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

在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); } } } 

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

它说:

属性或索引器’IFoo.TestFoo’无法分配 – 它是只读的。

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

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

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


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

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

 public class Impl : IFoo { private readonly string _testFoo; string IFoo.TestFoo => _testFoo; public Impl(string value) { _testFoo = value; } } 

我想你想要这个

上述就是C#学习教程:使用仅限getter的自动属性(C#6function)显式实现接口分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 string IFoo.TestFoo { get; } = "World"; 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/991496.html

(0)
上一篇 2021年12月23日
下一篇 2021年12月23日

精彩推荐