gpt4 book ai didi

c# - 如何以只读方式公开类中的私有(private)对象?

转载 作者:行者123 更新时间:2023-12-02 14:28:43 25 4
gpt4 key购买 nike

假设我有一个简单的类,其中包含一堆属性或属性:

internal class ConnectionProperties
{
internal string Name = "Default Name";
internal bool Enabled = false;
}

这些在名为 Data 的类中使用:

internal class Data
{
private ConnectionProperties _connection;

internal Data()
{
this._connection = new ConnectionProperties();

// Business logic to configure connection
this._connection.Name = "My Connection";
this._connection.Enabled = true; _
}

}

如何允许外部访问 _connection 的属性和值,而不允许从 Data 类之外的任何地方更改它们。

我知道我可以添加一个属性,例如

internal ConnectionName => _connection.Name;

但这感觉非常困惑并且可能很难维护

最佳答案

如果您控制 ConnectionProperties 类型,则可以使其实现一个接口(interface),例如 IReadOnlyConnectionProperties,这将公开其成员的只读 View 。

public interface IReadOnlyConnectionProperties 
{
string Name { get; }
bool Enabled { get; }
}

如果您不控制类型,您可以创建一个这样的接口(interface)并创建一个将实现它的包装类型。它将在其构造函数中使用 ConnectionProperties 并代理对其属性的获取访问。同样的方式ReadOnlyCollection确实如此。

internal ReadOnlyConnectionProperties : IReadOnlyConnectionProperties 
{
private readonly ConnectionProperties _wrapped;

public string Name => _wrapped.Name;
public bool Enabled => _wrapped.Enabled;

public ReadOnlyConnectionProperties(
ConnectionProperties connectionProperties) =>
_wrapped = connectionProperties;
}

请注意,这假定用户具有一定程度的信任。如果使用第一个解决方案,则没有什么可以阻止使用者将接口(interface)升级回 ConnectionProperties。第二种解决方案避免了这个问题,也是我推荐的。请记住,在这两种情况下,对底层 ConnectionProperties 的更改都将反射(reflect)在您向消费者提供的任何代理中。

关于c# - 如何以只读方式公开类中的私有(private)对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59592156/

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