静态类最大特性:
- 无需也无法实例化
- 静态类只能有静态的方法
- 无论对一个类创建多少个实例,它的静态成员都只有一个副本(这也是我这个场景需要使用的原因)
- 静态方法不可使用this:
- this代表的是调用这个函数的对象的引用,而静态方法是属于类的,不属于对象,静态方法成功加载后,对象还不一定存在.
静态方法不可使用this因为静态方法不针对任何实例对象。实例对象调用静态方法会因参数中多出一个指向自己的指针(this)而发生错误。
而静态方法与对象无关,根本不能把对象的引用传到方法中,所以不能用this
public static class Test {
public static IList<int> iList = new List<int>(100);
public static void MethodA() {
// coding...
iList.Add(0); // 这样是可以的。静态方法中访问静态成员
}
public void MethodB() {
// coding...
MethodA(); // 这样是【错误】的。在非静态方法里尝试访问静态成员
iList.Add(1); // 这样是【错误】的。道理一样
}
}
public class TryGo {
public void Go() {
Test.MethodA(); // 这样可以访问,通过类名直接访问静态方法
Test.iList.Add(2); // 这样可以访问,通过类名访问静态属性
Test t = new Test();
t.MethodB(); // 这样可以访问,通过实例访问非静态成员
t.MethodA(); // 这样是【错误】的,实例不能访问静态成员
t.iList.Add(3); // 这样是【错误】的,实例不能访问静态成员
}
}
My Code:
static class CardConfig
{
private static List<string> selectedCards = new List<string>();
// "CardConfig.tsv"只会被读取一次,不会调用一次函数就加载一次
static CardConfig()
{
StreamReader sr = new StreamReader("CardConfig.tsv");
string line;
while ((line = sr.ReadLine()) != null)
{
selectedCards.Add(line.Trim().ToLower());
}
}
static public bool isInCardConfig(string card)
{
return selectedCards.Contains(card.ToLower());
}
}
public class Test
{
public static void Main()
{
Console.WriteLine(CardConfig.isInCardConfig("test"));
}
}