在C#中,要确保一个类是不可变的,可以采用以下几种方法:
public class ImmutableClass
{
public readonly int Property1;
public readonly string Property2;
public ImmutableClass(int property1, string property2)
{
Property1 = property1;
Property2 = property2;
}
}
private
或protected
修饰符,确保类的属性或方法只能在类内部访问。这样,外部代码就无法修改类的属性或调用修改属性的方法。public class ImmutableClass
{
private int property1;
private string property2;
public ImmutableClass(int property1, string property2)
{
this.property1 = property1;
this.property2 = property2;
}
public int GetProperty1()
{
return property1;
}
public string GetProperty2()
{
return property2;
}
}
public class ImmutableClass
{
public int Property1 { get; }
public string Property2 { get; }
public ImmutableClass(int property1, string property2)
{
Property1 = property1;
Property2 = property2;
}
}
System.Collections.Immutable
库提供的不可变集合类型,如ImmutableList<T>
,ImmutableDictionary<TKey, TValue>
等。using System.Collections.Immutable;
public class ImmutableClass
{
public ImmutableList<int> Property1 { get; }
public ImmutableDictionary<string, string> Property2 { get; }
public ImmutableClass(IEnumerable<int> property1, IDictionary<string, string> property2)
{
Property1 = property1.ToImmutableList();
Property2 = property2.ToImmutableDictionary();
}
}
通过以上方法,可以确保C#中的类是不可变的。这样可以提高代码的安全性和可靠性,避免意外的属性值修改。同时,不可变类也更容易进行并发编程和缓存等优化。
领取专属 10元无门槛券
手把手带您无忧上云