c# - 带有 set 方法的接口(interface)仅用于初始化?

标签 c# methods interface

我正在尝试将所有参数更改为接口(interface)而不是类实例。 然而,当我尝试这个时,我遇到了一个问题,我需要向接口(interface)添加很多 set 方法,而我只想在其中添加 get 方法。原因是方法用于初始化,并且在初始化期间只需要一次 set 方法.

示例:

 protected IPcgMemory CurrentPcgMemory { get; private set; }

 protected PatchesFileReader(IPcgMemory currentPcgMemory, byte[] content)
 {
     CurrentPcgMemory = currentPcgMemory;
     CurrentPcgMemory.Content = content;
 }

错误:IMemory.Content 没有 setter (在最后一行)

public interface IPcgMemory : IMemory, INavigable
    ...

public interface IMemory : ...
    byte[] Content { get; }

我只想要IMemory for Content接口(interface)中的get方法,而不想要set方法。 我是否应该删除接口(interface)并使用 currentPcgMemory 的实例,例如:

 protected PatchesFileReader(PcgMemory currentPcgMemory, byte[] content)

或者我应该在内容中提供该集,例如:

public interface IMemory : ...
    byte[] Content { get; set; }

或者有更好的解决方案吗?

最佳答案

实现接口(interface)的实例的初始化是公共(public)“接口(interface)”的一部分。具有仅具有 getter 属性的接口(interface)意味着设置永远不可能。

不存在仅用于最常执行的操作的界面概念。

另一方面,如果您想要将引用传递给一个可以初始化实例的层,然后该层将引用传递给其他只能读取它的层,那么您可以使用两个接口(interface):

public interface IReadable {
    int SomeProperty {get;}
}

public interface IInitializable : IReadable {
    int SomeProperty {get;set;}
}

IReadable _passItOn;
public void InitializeAndUse(IInitializable initAndUse){
    _passItOn = initAndUse;
    initAndUse.SomeProperty = 42;

    UseReadOnly(_passItOn);
}

关于c# - 带有 set 方法的接口(interface)仅用于初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27538183/

相关文章:

python - 如何在 Python 中检查对象具有的方法?

haskell - 从具有函数作为 Haskell 中的字段的数据类型派生 Eq 时出现问题

java - 为什么我的 java 类实现了我不期望的方法?

C#:在接口(interface)中定义方法

c# - 关于Unity3D的继承行为的问题

c# - ListView ItemDataBound - 确定项目是否为 AlternatingItem?

c# - ASP.NET MVC 动态 View

JavaScript 使用 DOM 方法和属性

java - 为分层实体设计界面

c# - 从 Gmail 下载电子邮件并保存到 SQL 服务器的脚本?