c# - 引用类型只读属性 - 真的吗?

标签 c#

在我的 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
   }
}

最佳答案

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

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

你仍然可以说 f.Bar1.Prop = 1; 但是因为 readonly 你不能做 f.Bar1 = null; 。 Bar2 也一样。

关于c# - 引用类型只读属性 - 真的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21278134/

相关文章:

c# - 模型 - View - 发布者作为设计模式?

C# 在运行时创建构造函数

c# - PInvoke "Attempted to read or write protected memory"

c# - 如何将错误消息传递给 MVC 5 中的错误 View ?

c# - 将 out 修饰符的值返回到 C# 中的集合

c# - ActionResult<FileResult> 未按预期工作

c# - SL 5 脱离浏览器,提升信任度 - 从任何本地目录显示 PNG

C# Json.net 将嵌套的 json 反序列化为字符串

c# - 蛮力- c#

c# - Selenium ChromeDriver 在短时间内逐渐变慢