C# (初入江湖) -属性&索引&命名空间&using
属性与索引
属性
- 属性(Property) 是类(class)中的成员(字段)
- 属性具有set和get方法,set和get方法是属性的访问器
class PersonTest
{
// 没有显示声明get;set;方法 ,默认是有的
public string name;
}
public class PersonTest
{
// 显示的声明get和set方法。 其实效果与上面等同
public string name{ get; set; }
}
public class PersonTest
{
//自定义,即声明一个field控制属性赋值读取。效果与上面等同
private string name;
public string name
{
get { return name; }
set { name = value; }
}
}
public class PersonTest
{
// 私有化set方法,并给属性一个默认值,从而控制从外部只能读取属性,不能修改属性
public string name{ get; private set; } = "zhangsan";
}
索引器(indexer)
- 索引也称为角标,在程序中角标都是从0开始
- 索引器类似于属性。很多时候,创建索引器与创建属性所使用的编程语言特性是一样的
- 语法如下:
修改符 类型 this[参数列表]
{
set
{
}
get
{
}
}
在实际中的应用
internal class IndexerRecord
{
private string[] date = { "a", "b", "c", "d" };
public string this[int index]
{
set
{
if(index >=0 && index < date.Length)
{
date[index] = value;
}
}
get
{
if (index >= 0 && index < date.Length)
{
return date[index];
}
return null;
}
}
}
internal static class Program
{
static void Main()
{
// 通过索引器获取数据
IndexerRecord indexerRecord = new IndexerRecord();
string a = indexerRecord[0];
Console.WriteLine(a); //output: a
//修改数据,通过索引器重新赋值
indexerRecord[0] = "aaa";
a = indexerRecord[0];
Console.WriteLine(a); //output: aaa
}
}
属性与索引器的区别
属性 | 索引器 |
---|---|
通过名称标识 | 通过参数列表进行标识 |
通过简单的名称访问 | 通过 [ ] 来访问 |
可以用static修饰 | 不能用static修饰 |
属性的get访问器没有参数 | 索引的get访问器具有与索引相同的参数列表 |
属性的set访问器包含隐式的value参数 | 除了value参数外,索引的set访问器还有与索引相同的参数列表 |
命名空间&using导包
命名空间
- 两个作用
- .NET 使用命名空间来组织和管理它的许多类;
- 如:System.Console.WriteLine(“Hello World!”);
- System 是一个命名空间,Console 是该命名空间中的一个类
- 如果使用 using 关键字的话,就不必使用完整的名称
- 在较大的编程项目中,声明自己的命名空间可以帮助控制类和方法名称的范围
- .NET 使用命名空间来组织和管理它的许多类;
using System;
Console.WriteLine("Hello World!");
- 命名空间的语法如下:
namespace 名称
{
}
namespace 人蛇大战
{
/// 人类
public class Person
{
}
/// 蛇类
public class snake
{
}
}
using指令
- 定义:using 指令允许使用在命名空间中定义的类型,而无需指定该类型的完全限定命名空间
- 作用:
- 引用命名空间
- 为命名空间或类型创建别名
- using 块里边可以写代码逻辑并执行,执行超出using 域后,变量(连接)在内存中会被自动释放掉
internal class UsingDemo
{
static void Main()
{
// 第一种用法, 引入命名空间
Console.WriteLine("hello");
// 第二种用法, 采用别名的形式(将字典对象取了一个map别名)
Map map=new Map();
map.Add("hello", "222");
//第三种方式,执行using 块,执行完后自动释放对象(创建并写入一个文件)
Byte[] bytesToWrite = new Byte[] { 1, 2, 3, 4, 5};
using (FileStream fs = new FileStream("aa.txt", FileMode.Create))
{
//将字符串写入临时文件
fs.Write(bytesToWrite, 0, bytesToWrite.Length);
}
}
}
更多好看的内容和好玩的案例请关注我的微信公众号: 程序猿知秋