我有一个(公共(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 时遇到的问题的示例:
最佳答案
您可以使用该属性的 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/