属性如何具有属性和方法?

时间:2011-09-16 18:13:30

标签: c# .net asp.net

我很惊讶地看到属性可以有更多的属性和方法。为了更好地理解它,我们举个例子:

Panel1.Controls.Add();// Here Panel is object and Controls is Property and Add() is a Method.
Panel1.Controls.Count;// Here Panel is object and Controls is Property and Count is Property.

有人可以解释一下我们如何在班级中创造这样的行为 感谢。

3 个答案:

答案 0 :(得分:10)

Controls是一个返回ControlCollection的属性 - 所以你的第二个语句是这样的:

ControlCollection collection = Panel1.Controls;
int count = collection.Count;

这更有意义吗?它没有调用属性本身的下一个方法/属性;它是在评估属性的结果上调用它。

答案 1 :(得分:6)

它是面向对象编程的核心。

该属性可以是具有自己属性的复杂类型。

class Car{

    Engine CarEngine {get ; set; }
}

class Engine 
{
    int Cylinders {get; set; }
}

这里的汽车有一个属性引擎。和引擎拥有自己的财产。所以,如果你有一辆汽车的实例,你可以myCar.CarEngine.Cylinders

答案 2 :(得分:1)

Controls是Panel1的一个属性,但该属性是Object类型,任何对象都可以有属性和方法。

相关问题