我已经阅读了msdn.microsoft指南,以下是一个例子:
// public class:
public class Tricycle
{
// protected method:
protected void Pedal() { }
// private field:
private int wheels = 3;
// protected internal property:
protected internal int Wheels
{
get { return wheels; }
}
}
它允许我通过Trycicle.Wheels访问其他类中的wheel变量,对吗? 但是有些属性需要实例化,似乎可以实现一些访问
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
class Program
{
static void Main()
{
TimePeriod t = new TimePeriod();
// Assigning the Hours property causes the 'set' accessor to be called.
t.Hours = 24;
// Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine("Time in hours: " + t.Hours);
}
}
// Output: Time in hours: 24
在这个例子中,我必须实例化一个TimePeriod对象,这是否意味着我无法在不实例化的情况下访问'seconds'变量的值?为什么这个例子和前一个例子有这样的区别?是什么迫使我实例化?
我对这些概念不是很熟悉。
答案 0 :(得分:1)
您应该研究静态与实例成员。
在这个例子中:
public class Tricycle {
public static readonly int Wheels = 3;
public string Color {get; set;}
}
所有三轮车的属性是它们有3个轮子。因此,我将Wheels
字段设为静态,您可以要求Tricycle.Wheels
。
但是,并非每个三轮车都是相同的颜色,因此Color
不是静态的,因此您需要一个特定的三轮车(一个实例)来获取或设置其颜色。