[英]Reference type read-only properties - Really?
In my DDD pattern, I am exposing SqlConnection read-only property to my DAL class object. 在我的DDD模式中,我将SqlConnection只读属性暴露给我的DAL类对象。 But as SqlConnection is reference type, I can still call .Dispose() method eventhough it's read-only. 但是由于SqlConnection是引用类型,即使它是只读的,我仍然可以调用.Dispose()方法。
The same thing happened to List<> which I resolved by converting it to ReadOnlyCollection but I happen to use many other core .NET reference type object as read-only property and cannot afford to create wrapper class. 同样的事情发生在List <>上,我通过将其转换为ReadOnlyCollection来解决,但是我碰巧使用许多其他核心.NET引用类型对象作为只读属性,并且无法创建包装器类。
Any resolution? 有什么解决方法吗?
Added code: 添加的代码:
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
}
}
The readonly
modifier only applies to the reference, not to the actual instance (being referenced). readonly
修饰符仅适用于引用,不适用于实际实例(被引用)。
class Foo
{
public readonly Bar Bar1;
public Bar Bar2 { get; }
...
}
You can still say f.Bar1.Prop = 1;
您仍然可以说f.Bar1.Prop = 1;
but because of the readonly
you can't do f.Bar1 = null;
但是由于readonly
您不能执行f.Bar1 = null;
. 。 The same for Bar2. 对于Bar2也是一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.