屬性:
using System;
class MyClass
{
private int MyInt;
public int MyProperty
{
get { return MyInt; }
set { if (value >= 0) MyInt = value; else MyInt = 100; }
}
}
class Program
{
static void Main()
{
MyClass obj = new MyClass();
obj.MyProperty = 2009;
Console.WriteLine(obj.MyProperty); //2009
obj.MyProperty = -1;
Console.WriteLine(obj.MyProperty); //100
Console.ReadKey();
}
}
只讀屬性:
using System;
class MyClass
{
private int MyInt = 100;
public int MyProperty
{
get { return MyInt; }
}
}
class Program
{
static void Main()
{
MyClass obj = new MyClass();
Console.WriteLine(obj.MyProperty); //100
Console.ReadKey();
}
}