本系列第二篇,剖析 Common/Fcl.cs,提供 .NET Compact Framework 缺失的 API 相容實作,包括 Environment.NewLine、File.ReadAllText/WriteAllText、Point + Size 運算、Array.Resize 等。
namespace Skyiv.Ben.PushBox.Common
{
static class Fcl
{
// Environment.NewLine 相容
public static string NewLine => "\r\n";
// File.ReadAllText 相容
public static string ReadAllText(string path)
{
string text = "";
if (File.Exists(path))
{
using (var sr = new StreamReader(path, Pub.Encode))
text = sr.ReadToEnd();
}
return text;
}
// File.WriteAllText 相容
public static void WriteAllText(string path, string contents)
{
using (var sw = new StreamWriter(path, false, Pub.Encode))
sw.Write(contents);
}
// Point + Size 運算(CF 缺少)
public static Point Add(Point point, Size size) =>
new Point(point.X + size.Width, point.Y + size.Height);
// Array.Resize 泛型實作(CF 2.0 缺少)
public static void Resize(ref T[] array, int newSize)
{
if (array != null && array.Length == newSize) return;
if (array == null) array = new T[0];
var newArray = new T[newSize];
Array.Copy(array, newArray, Math.Min(array.Length, newArray.Length));
array = newArray;
}
}
}
| 方法 | CF 缺失原因 | 實作策略 |
|---|---|---|
NewLine | CF 無 Environment.NewLine | 硬編碼 \r\n,Windows 行尾標準 |
ReadAllText/WriteAllText | CF 無靜態便利方法 | 封裝 StreamReader/Writer,指定編碼 Pub.Encode (GB2312) |
Point.Add | CF Point 無 + 運算子 | 手工實作座標加法 |
Array.Resize | CF 2.0 無泛型 Array.Resize | 手工配置新陣列、複製、交換參考 |
Pub.Encode = Encoding.GetEncoding("GB2312"),避免中文亂碼(CF 6.0 不支援 GB18030)。Resize 展示 CF 2.0 支援泛型方法,雖無 Array.Resize 靜態方法。static class Fcl 防止實例化,方法皆為純函式,執行緒安全。Fcl.cs 填補 CF 與完整 Framework API 差距,是跨平台核心庫的基石。下一篇將介紹 Block.cs 定義遊戲基本單元格與狀態編碼。