c# - 在实现上实现接口(interface)的 `internal set` 属性

标签 c# oop

我有一个(公共(public))接口(interface),IAuditLogConfig,它有一个带有公共(public) getter 和内部 setter 的属性:

public interface IAuditLogConfig
{
    int ElementTypeId { get; internal set; }
    
    // ...and other methods
}

此接口(interface)的实现是通过位于同一库中的工厂实例化的,该工厂将设置 ElementTypeId 属性。

public IAuditLogConfig Create(int elementTypeId)
{
    var key = ...;
    var auditLogConfig = _auditLogConfigFactory.ComponentExists(key)
                             ? _auditLogConfigFactory.CreateComponent(key)
                             : new GenericAuditLogConfig();

    auditLogConfig.ElementTypeId = elementTypeId;
    
    return auditLogConfig;
}

但是如何在实现类上声明此属性?

这是我在同一库中的 GenericAuditLogConfig 类上声明 setter 时遇到的问题的示例:

enter image description here

最佳答案

您可以使用该属性的 setter 创建一个单独的内部接口(interface)。由于该接口(interface)是内部的,因此不能在程序集外部使用该接口(interface)。

显式对从工厂返回的每种类型实现 IHasElementTypeIdSettable,您应该可以开始了!

    internal interface IHasElementTypeIdSettable
    {
        // since the class is internal already, you can choose 
        // to leave out the internal keyword on the setter.
        int ElementTypeId { get; internal set; }
    }

    public interface IAuditLogConfig
    {
        int ElementTypeId { get; }
    }

    public class GenericAuditLogConfig : IHasElementTypeIdSettable, IAuditLogConfig
    {
        private int _elementTypeId;

        // exposes a public getter.
        public int ElementTypeId { get { return _elementTypeId; } }

        // explicit implementation of IHasElementTypeIdSettable results in a
        // public getter and setter when cast to the internal interface: IHasElementTypeIdSettable
        // this results in the getter and the setter also being internal
        int IHasElementTypeIdSettable.ElementTypeId
        {
            get { return _elementTypeId; }
            set { _elementTypeId = value; }
        }
    }

    public IAuditLogConfig Create(int elementTypeId)
    {
        var key = ...;
        var auditLogConfig = _auditLogConfigFactory.ComponentExists(key)
                                 ? _auditLogConfigFactory.CreateComponent(key)
                                 : new GenericAuditLogConfig();

        ((IHasElementTypeIdSettable)auditLogConfig).ElementTypeId = elementTypeId;

        return auditLogConfig;
    }

关于c# - 在实现上实现接口(interface)的 `internal set` 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65505254/

相关文章:

c# - UE4(虚幻引擎4)集成LuaJit时出现LNK2005错误

c# - BigIntegers 的 ArrayList 到字节数组

php - 类型提示抽象类单例

c# - 如何让枚举存储每个条目的额外信息

php - 两个查询与一个查询,性能

javascript - 这两种继承有什么区别?

python - 在 python 中对静态函数进行分组的适当方法

c# - 使用 GetProperty 语法在 Umbraco 7 中获取媒体 url

c# - 在 C# 中使用 linq 从列表中的每一行获取第 n 个单词

javascript - 带有 JavaScript 文件的 HTML 无法在 WPF 应用程序内的 WebView2 上运行