【发布时间】:2019-03-02 11:58:43
【问题描述】:
我正在尝试了解 Field 的正确用法以及是否应允许其他类访问该字段还是应该始终通过属性访问该字段?
考虑一下我有如下代码:
internal class MyCalculator : IDisposable
{
public Type1 type1;
public MyCalculator(Type1 type1)
{
this.type = type1;
}
}
internal class Accessor
{
public void Foo()
{
MyCalculator obj = new MyCalculator();
obj.type1.Id = 10;
}
}
这是允许访问另一个类之外的公共字段的好习惯,还是应该始终只通过属性?
当我检查 List 的源代码时,我看到了这个:
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
{
private const int _defaultCapacity = 4;
private T[] _items;
[ContractPublicPropertyName("Count")]
private int _size;
private int _version;
}
私有属性标有下划线,而相同的字典私有成员未标有下划线,如下所示:
public class Dictionary<TKey,TValue>: IDictionary<TKey,TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback {
private struct Entry {
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
private int[] buckets;
private Entry[] entries;
private int count;
private int version;
private int freeList;
private int freeCount;
}
所以我有点困惑上面 2 之间有什么区别,即 List 和 Dictionary 私人成员,或者我可能遗漏了什么?
这并不完全是重复的,因为我问了太多事情,当然我可以在问题中提到这一点,但因为我不希望我的标题问题太大。
此外,我在我的代码(字段和属性代码 sn-p)中显示的内容以及在我的特定场景中是否是一个好的做法。
【问题讨论】:
标签: c#