ten*_*npn 78 c# theory const-correctness
const-correctness的要点是能够提供用户无法更改或删除的实例的视图.编译器支持这一点,指出何时从const函数中断开constness,或者尝试使用const对象的非const函数.因此,如果不复制const方法,我可以在C#中使用具有相同目的的方法吗?
我知道不变性,但这并不能真正地将容器对象转移到一个例子.
Tra*_*rap 62
我也经常遇到这个问题并最终使用接口.
我认为重要的是放弃C#是任何形式的想法,甚至是C++的演变.它们是两种不同的语言,它们的语法几乎相同.
我通常通过定义类的只读视图来表达C#中的'const correctness':
public interface IReadOnlyCustomer
{
String Name { get; }
int Age { get; }
}
public class Customer : IReadOnlyCustomer
{
private string m_name;
private int m_age;
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public int Age
{
get { return m_age; }
set { m_age = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*Sam 28
为了获得const-craziness(或函数式编程术语中的纯粹)的好处,您需要以某种方式设计类,使它们是不可变的,就像c#的String类一样.
这种方法比仅将对象标记为只读更好,因为使用不可变类,您可以在多任务环境中轻松传递数据.
Ric*_*ich 23
我只想告诉你,许多System.Collections.Generics容器都有一个AsReadOnly方法,它会返回一个不可变的集合.
| 归档时间: |
|
| 查看次数: |
14721 次 |
| 最近记录: |