【问题标题】:Reference type read-only properties - Really?引用类型只读属性 - 真的吗?
【发布时间】:2014-01-22 08:50:05
【问题描述】:

在我的 DDD 模式中,我将 SqlConnection 只读属性公开给我的 DAL 类对象。但是由于 SqlConnection 是引用类型,我仍然可以调用 .Dispose() 方法,即使它是只读的。

同样的事情发生在 List 上,我通过将其转换为 ReadOnlyCollection 解决了这个问题,但我碰巧使用了许多其他核心 .NET 引用类型对象作为只读属性并且无法创建包装类。

有什么解决办法吗?

添加代码:

public class DbContext
{
    public SqlConnection sqlConnection {get; private set; }
}

public class caller
{
   public caller()
   {
       var dbContext = new DbContext();
       dbContext.sqlConnection.Dispose(); // Want to hide Dispose() method
   }
}

【问题讨论】:

  • 也许你应该用(伪)代码显示你想要实现的目标,因为它根本不清楚。
  • 为什么你的类需要暴露一个SqlConnection实例?
  • 只读属性意味着你不能重新分配它,并不是说你不能弄乱它引用的值。
  • 不要暴露连接。
  • 即使你在直接访问属性时设法隐藏了Dispose(),如果你的属性是SqlConnection,也没有什么能阻止调用者将它传递给其他需要SqlConnection 参数,并让其他方法调用 Dispose()

标签: c#


【解决方案1】:

readonly 修饰符仅适用于引用,而不适用于实际实例(被引用)。

class Foo
{
    public readonly Bar Bar1;
    public Bar Bar2 { get; } 
    ...
}

你仍然可以说 f.Bar1.Prop = 1; 但由于 readonly 你不能说 f.Bar1 = null; 。 Bar2 也是如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 2016-03-24
    • 2020-05-03
    • 2018-09-13
    • 2016-05-24
    • 2012-01-01
    • 2011-11-08
    相关资源
    最近更新 更多