C# Array,ArraryList,泛型,构造方法,HashTable,类型转换与字符串格式化
利用Array类判断元素是否存在于数组中
Array.IndexOf(数组, 元素)
可以返回元素在数组中的位置,如果数组中没有元素,返回-1
.通过判断返回值是否为-1
可以判断元素否是在数组中.
int[] intArray = {10000, 10086, 10010};
if (!(Array.IndexOf(intArray, 10086)==-1)){... ;}
构造方法
构造方法是生成对象实例时调用的方法,可以用于初始化对象中的值.注意,给对象中属性赋值需要使用this
关键字,与Python不同,C#是隐式的以this
关键字表示对象本身,不像Python习惯显式用self
指代.
泛型
在一个类中需要用到泛型时需要在定义类的时候就指定泛型占位符.然后再在类中具体使用,而不是在类里面声明使用泛型.
动态数组
动态数组与Pyhton中的list极其相似,可以直接对其进行增删改,ArrayList中的元素类型也不要求统一.与普通数组不同的是,获取其长度的属性是Count
而非Length
.
动态数组内没有元素时和null
是一种情况吗?不是一种情况,如果没有使用new
,会是一个未赋值的变量,方法内进行操作会引起编译器报错,类中定义未赋值(装箱后不赋值)编译检查时不会报错,而运行时会引发null
错误.
public class Test
{
public ArrayList listInClass;
}
internal class Program
{
static void Main(string[] args)
{
var testClass = new Test();
if (testClass.listInClass is null)
{
Console.WriteLine("listInClass is null."); // 输出
// testClass.listInClass.Add(10086);
// 运行时报错: System.NullReferenceException:
// “Object reference not set to an instance of an object.”
}
// ArrayList testList; if (testList is null) {...}
// 编译器报错 "使用了未赋值的局部变量testList."
var testList = new ArrayList();
if(testList is null)
{
Console.WriteLine("testList is null.");
}
else
{ // 输出 testList length = 0.
Console.WriteLine($"testList length = {testList.Count}");
}
}
}
字符串格式化
不像Python中格式化是默认的,需要调用String
类中的Format
方法.但类似的$
字符串不用额外调用String.Format()
,直接将变量名放到槽中即可,如Python中的f"{var}"
一样:$"{var}"
.
HashTable
能否使用赋值号直接添加,绕过Add()
方法?可以的
static void Main(string[] args)
{
Hashtable testHt = new Hashtable();
Console.WriteLine("Hashtable testHt = new Hashtable();");
Console.WriteLine($"testHt.Count = {testHt.Count}"); // 0
testHt["key1"] = 10086;
Console.WriteLine("testHt[\"key1\"] = 10086;");
Console.WriteLine($"testHt.Count = {testHt.Count}"); // 1
testHt.Add("key2", 10010);
Console.WriteLine("testHt.Add(\"key2\", 10010);");
Console.WriteLine($"testHt.Count = {testHt.Count}"); // 2
}
类型转换
Convert
, Parse
, ToString()
类型转换的区别.Parse
是用来将字符串转换为目标类型的方法,在目标类型的基础上调用.Convert
将指定值转换为目标类型.ToString()
将支持的类型直接转换为字符串,继承于Object.ToString
.
目标类型 变量名 = 目标类型.Parse(字符串);
目标类型 变量名 = Convert.To目标类型(值);
string 变量名 = 值.ToString(格式控制串);