gpt4 book ai didi

c# - 在实现内部可读/可写的只读接口(interface)属性

转载 作者:行者123 更新时间:2023-11-30 13:56:32 26 4
gpt4 key购买 nike

我想要一个

interface IFoo
{
string Foo { get; }
}

实现如下:

abstract class Bar : IFoo
{
string IFoo.Foo { get; private set; }
}

我希望该属性可以通过接口(interface)获取,但只能在具体实现中写入。最干净的方法是什么?我需要“手动”实现 getter 和 setter 吗?

最佳答案

interface IFoo
{
string Foo { get; }
}


abstract class Bar : IFoo
{
public string Foo { get; protected set; }
}

几乎与您拥有的一样,但 protected 并从类的属性中删除 IFoo.

我建议 protected 假设您只希望它可以从派生类的内部访问。相反,如果您希望它完全公开(也可以在类外设置),只需使用:

public string Foo { get; set; }

关于c# - 在实现内部可读/可写的只读接口(interface)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26937170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com