class SetGet
{
private string s;
public string S
{
set
{
//这里可以使用条件进行限制
s = value;
}
get
{
return s;
}
}
public static void Main(string[] a)
{
SetGet s = new SetGet();
s.s = Console.ReadLine(); Console.WriteLine(s.s); } }
总结:
c#中的属性:
属性是这样的一种成员:提供了使外部类安全、灵活地访问类中私有字段(类中的字段默认就是私有的)的解决方案。属性实际上是一种成员方法。用法如上
当属性中只有set{}时就是只写属性
当属性中只有get{}时就是只读属性
当属性添加了static修饰符后,就属于整个类而不是实例。
属性通过使用访问器读取和写入类中的字段,对字段进行保护。这实际上是按封装思想设计的,通过封装,可以避免非法数据的访问,保证数据的完整性。<br>
静态成员属于类本身而不是属于实例本身。
此类演示静态成员的用法。
class Dog
{
public static int count = 0;
public Dog()
{
count++;//实现计算创建的本类的实例的个数
}
static void Main(string[] args)
{
Dog d1 = new Dog();
Dog d2 = new Dog();
Console.WriteLine(count);
}
}
索引器
索引器(Indexer)是C#引入的一个新型的类成员,它使得对象可以像数组那样被方便,直观的引用。
class Album
{
// 该数组用于存放照片
Photo[] photos; // album的字段,默认private
public Album(int capacity)// 构造器初始化一个相册时要指定能存多少张照片
{
photos = new Photo[capacity];
}
public Photo this[int index]
{
get
{
// 验证索引范围
if (index < 0 || index >= photos.Length)
{
Console.WriteLine("索引无效");
// 使用 null 指示失败
return null;
}
// 对于有效索引,返回请求的照片
return photos[index];
}
set
{
if (index < 0 || index >= photos.Length)
{
Console.WriteLine("索引无效");
return;
}
photos[index] = value;
}
}
public Photo this[string title]
{
get
{
// 遍历数组中的所有照片
foreach (Photo p in photos)
{
// 将照片中的标题与索引器参数进行比较
if (p.Title == title)
return p;
}
Console.WriteLine("未找到");
// 使用 null 指示失败
return null;
}
}
static void Main(string[] args)
{
Album friends = new Album(3);// 创建一个容量为 3 的albulm freindes
Photo first = new Photo("Jenn"); // 创建 3 张照片
Photo second = new Photo("Smith");
Photo third = new Photo("Mark");
friends[0] = first; // 向相册加载照片
friends[1] = second;
friends[2] = third;
Photo obj1Photo = friends[2]; // 按索引检索
Console.WriteLine(obj1Photo.Title);
// 按名称检索
Photo obj2Photo = friends["Jenn"];
Console.WriteLine(obj2Photo.Title);
}
}
class Photo
{
string _title;//photo的字段title
public Photo(string title)//构造器,初始化一张photo时请输入标题
{
this._title = title;
}
public string Title//title的只读属性
{
get
{
return _title;
}
}
}