我最初创建了一个不可变的类,但现在我希望可以选择创建一个不可变的等效数据结构。假设,例如,可变类:
namespace Utility
{
public class bar
{
public string name { get; set; }
public double weight { get; set; }
public int age { get; set;}
public List<...> friendInstances; //instantiated at run time
}
}
//and now I make a mutable class.
public class MemorySafe_bar
{
private readonly string _name;
private readonly double _weight;
private readonly int _age;
private readonly List<...> _friendInstances;
public MemorySafe_bar(string name, double weight, int age,
List<...> friend Inst)
{
_name = name;
_weight = weight;
_age = age;
_friendInstances = Inst
}
//..getters would go here...
function()
{
Utility.bar bar_ex = new bar();
bar_ex.name = "Kathy";
bar_ex.weight = 42.34;
bar_ex.age = 10;
bar_ex.List<...> friends = new List<...>();
friends.Add(stuff);
Utility.MemorySafe_bar = new MemorySafe_bar(
bar_ex.name, bar_ex.weight, bar_ex.age, friends);
}
}
从现在开始,我不相信可变对象将来会被更改。