c# - 字段和属性如何关联?

标签 c#

我正在阅读的一本书(Wrox Beginning Visual C# 2012,到目前为止是一本很棒的书)在示例中使用了此类:

class Farm<T> : IEnumerable<T> where T : Animal
{
    private List<T> animals = new List<T>();

    public List<T> Animals
    {
        get
        {
            return animals;
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        return animals.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return animals.GetEnumerator();
    }
    //...
}

我的问题是:编译器如何“知道”属性“Animals”和字段“animals”是相关联的,这样当我在程序中实例化一个 Farm<Animal> 时然后说myFarm.Animals.Add(new Cow());对象被添加到私有(private)列表?我知道这是真的,因为我可以看到枚举器迭代了 animals因此当我说 foreach (Animal animal in myFarm)我在 animals 中看到了对象我之前添加到 Animals .

当我们讨论像 int 这样的简单字段时,这对我来说更有意义。在那种情况下,当我设置 MyInt=1 时似乎很明显这导致 myInt==1 ,这是因为该属性通过 set 链接到该字段访问器。

最佳答案

它“不知道”它们是“关联的”。它只是执行这段代码:

public List<T> Animals
{
    get
    {
        return animals;
    }
}

当你写 myFarm.Animals.Add(...) ,运行时为您的 Animals 执行 getter 方法属性(property)。此方法返回 animals (因为你就是这样写的)。 Add()然后在结果上调用方法。

我认为你的困惑可能是你觉得你正在“修改” Animals属性,因此你期望一个 set被涉及。不是这种情况。该属性只是一个获取或放置对 List<T> 类型对象的引用的地方。 .您不是在创建新列表或将引用点指向不同的列表。引用保持不变。您只是在所引用的对象上调用一个方法。这就是为什么只有属性的 getter 被调用的原因。

关于c# - 字段和属性如何关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22426747/

相关文章:

带有对象列表的 C# if 语句语法

c# - 将 Unity 中的 2D 相机移动限制在 map 的边缘

c# - 在 LINQ 哪里访问外键?

c# - UpdateModel() 有什么作用?

c# - C#中switch语句的多个变量

c# - 上传图片asp.net Core

c# - c#中如何从一个字符串中提取一个字符串

c# - 在运行时以静态方法获取当前类?

c# - 使用 INotifyPropertyChanged 绑定(bind)到 Silverlight 中的字典

c# - 无法使用必应 map 通过 mvvm 将 map 地理坐标中心绑定(bind)到 Windows Phone 上的 map