C# 语法教程
C# 语法教程 —— 写给 JavaScript/TypeScript 开发者
面向场景:用 Secs4Net 写 SECS/GEM 网关服务。每个知识点都和 JS/TS 对照着讲,标注了 ⭐ 的是写网关服务时一定会用到的。
0. 环境与第一个程序
# 安装 .NET SDK(推荐 8.0 LTS)后
dotnet new console -o MyGateway # 创建项目,类似 npm init
dotnet run # 运行,类似 npm run dev
dotnet add package Secs4Net # 装包,类似 npm install
C# 文件以 .cs 结尾,命名空间/类名与文件路径通常保持一致(但语言本身不强制)。
最小程序(C# 10+ 顶层语句,连 Main 都不用写):
Console.WriteLine("Hello, SEMI!");
1. 变量与类型系统 ⭐
C# 是静态强类型,TS 转过来会很亲切,但 C# 类型是真正运行时生效的。
// 显式类型
int deviceId = 1;
string host = "127.0.0.1";
bool isActive = true;
double timeout = 10.5;
// var = 类型推断(编译期确定,运行时仍是具体类型,不像 JS 的动态类型)
var port = 5000; // 就是 int
var sml = "S1F13 W"; // 就是 string
// 常量
const int MaxRetry = 3;
readonly int Timeout; // 只能在构造函数中赋值(实例字段)
基本类型对照表
| C# | JS/TS 对应 | 说明 |
|---|---|---|
int (32位) / long (64位) |
number |
整数有明确位数 |
double / decimal |
number |
decimal 精度更高,适合金额 |
string |
string |
不可变,同 JS |
bool |
boolean |
不能用真值判断,if(1) 编译不过 |
byte[] |
Uint8Array |
二进制数据 |
char |
无 | 单字符,用单引号 'a' |
null |
null/undefined |
没有 undefined,只有 null |
2. 字符串 ⭐
var name = "S1F13";
// 插值(和 JS 模板字符串一样)
var msg = $"Connecting to {host}:{port}";
var detail = $"Result: {result?.Name ?? "unknown"}"; // ?? 也存在
// 原始字符串(C# 11+,类似 JS 不转义)
var path = """C:\logs\secs.log""";
// 常用方法,几乎与 JS 同名
s.ToUpper(); s.ToLower(); s.Contains("S1"); s.StartsWith("S");
s.Split(','); string.Join(",", arr); s.Trim();
int.Parse("123"); 123.ToString(); // 类型转换
3. 集合:C# 没有“万能数组” ⭐
JS 里一个数组走天下,C# 按用途分类型:
// List<T> ≈ JS Array(最常用)
var devices = new List<string> { "ETCH01", "CVD02" };
devices.Add("ALD03");
devices.Remove("ETCH01");
devices.Count; // 注意:是属性 Count,不是方法 count()
// Dictionary<K,V> ≈ JS Map / 普通对象
var status = new Dictionary<string, int>
{
["ETCH01"] = 1,
["CVD02"] = 2,
};
status["ETCH01"] = 3;
status.TryGetValue("ETCH01", out int v); // 安全取值
// 数组(定长)
int[] codes = { 1, 13, 101 };
// HashSet<T> ≈ JS Set
var seen = new HashSet<string>();
LINQ ≈ JS 数组方法 ⭐⭐
LINQ 就是 C# 版的 map/filter/reduce,写法是方法链或 SQL 风格:
var alarms = new List<Alarm> { /* ... */ };
// filter + map
var names = alarms
.Where(a => a.Severity > 2) // filter
.Select(a => a.AlarmText) // map
.ToList(); // LINQ 是惰性的,要 ToList() 才执行
// find / findIndex
var first = alarms.FirstOrDefault(a => a.Alcd == 0x01); // 找不到返回 null
var idx = alarms.FindIndex(a => a.Alid == 137);
// some / every
bool hasError = alarms.Any(a => a.Severity > 3);
bool allAcked = alarms.All(a => a.IsAcked);
// sort
var sorted = alarms.OrderBy(a => a.Alid).ToList();
// reduce
int total = alarms.Sum(a => a.Severity);
// 另有 Max/Min/Average/Count/GroupBy/Distinct...
4. 控制流
// if/else、while、for 与 JS 几乎一样
for (int i = 0; i < 10; i++) { }
// foreach ≈ JS for...of
foreach (var alarm in alarms) { }
// switch 表达式(C# 8+,比 JS 的强很多,支持模式匹配)
string level = severity switch
{
>= 3 => "Critical",
>= 1 => "Warning",
_ => "Info" // _ ≈ default
};
// 类型判断
if (obj is string s) { /* s 已自动转型 */ }
if (obj is not null) { }
// ≈ JS 的 &&
5. 类与属性 ⭐⭐
C# 的“属性”是语法糖,≈ 带 getter/setter 的对象字段:
public class Alarm
{
// 自动属性 ≈ TS 的字段声明
public int Alid { get; set; }
public string AlarmText { get; set; } = "";
// 只读属性(计算属性)
public string Display => $"[{Alid}] {AlarmText}"; // => 是表达式属性
// 传统构造函数
public Alarm(int alid, string text)
{
Alid = alid;
AlarmText = text;
}
}
var alarm = new Alarm(137, "Vacuum error"); // new 一个类,没有对象字面量语法
record:不可变数据类 ⭐
≈ TS 的 interface + 不可变语义,一行顶很多代码:
public record AlarmInfo(int Alid, string Alcd, string AlarmText);
var a = new AlarmInfo(137, "1", "Vacuum error");
var b = a with { AlarmText = "Pump down" }; // 不可变拷贝 ≈ JS 展开运算符 {...a, ...}
// 值相等:a == new AlarmInfo(137,...) 按字段比较,JS 做不到
接口
public interface IDeviceChannel
{
Task ConnectAsync(string host, int port); // 接口方法不需要实现体
Task DisconnectAsync();
}
public class SecsChannel : IDeviceChannel // : 实现/继承,一个冒号搞定
{
public async Task ConnectAsync(string host, int port) { /* ... */ }
public Task DisconnectAsync() => Task.CompletedTask;
}
6. 空安全 ⭐⭐
TS 的 strictNullChecks 思想完全一致,但写法不同:
string name = null; // 编译警告:非可空类型不能为 null
string? name = null; // ? 声明可空 ≈ TS 的 string | null
// 安全访问
var len = name?.Length; // ≈ name?.length
var text = name ?? "default"; // ≈ name ?? "default"
name ??= "fallback"; // 空则赋值
name!.Length; // ! 断言非空 ≈ TS 的 !
7. 方法、参数
// 普通方法
public int Add(int a, int b) => a + b; // 表达式体方法(单行时可这样写)
// 可选参数(没有 JS 的对象解构参数惯用法,用可选参数或命名参数)
public void Send(string sml, int deviceId = 1, bool wait = true) { }
Send("S1F13 W", wait: false); // 命名参数,跳过中间的
// out 参数:一个方法返回多个值
public bool TryGetStatus(string id, out int code)
{
code = 1;
return true;
}
// 元组:≈ JS 多返回值
(string Host, int Port) ParseEndpoint(string s) => ("127.0.0.1", 5000);
var (host, port) = ParseEndpoint("..."); // 解构!很 JS
8. async/await ⭐⭐⭐(网关服务的核心)
概念和 JS 相同,但有本质区别:C# 的 await 是真多线程,不会阻塞、也不需要在所有地方层层标注。
// 返回类型:Task ≈ Promise
public async Task<string> ConnectAsync(string host, int port)
{
await channel.ConnectAsync(host, port); // await 用法一模一样
return "Connected";
}
// Task<T> ≈ Promise<T>;不带 T 的 Task ≈ Promise<void>
// ⚠️ 没有值的异步方法返回 Task,不是 async void(那个只用于事件处理器)
// 并发执行(≈ Promise.all)
var (sml, status) = (GetSmlAsync(), GetStatusAsync());
await Task.WhenAll(GetSmlAsync(), GetStatusAsync());
// 延时
await Task.Delay(3000); // ≈ setTimeout 的 Promise 化
// 超时控制(JS 里要手写 race,C# 有内置)
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await channel.ConnectAsync(host, port, cts.Token);
与 JS 的关键区别
| JS | C# | |
|---|---|---|
| 执行模型 | 单线程事件循环 | 线程池多线程 |
| await 之后 | 通常还在原线程 | 可能换线程! |
| 竞态风险 | 微任务间安全 | 共享状态需加锁 |
// 因为多线程,共享状态要保护(网关里连接状态、T5 计时器都涉及)
private readonly object _lock = new();
lock (_lock)
{
_state = State.Connected;
}
简单起步阶段记住一条:不要在多个线程同时读写同一个集合/字段;需要时用
ConcurrentDictionary<K,V>/ConcurrentQueue<T>。
9. 事件与委托 ⭐⭐(接收设备消息全靠它)
委托 ≈ 一等公民函数引用,事件 ≈ 发布订阅:
// Lambda ≈ 箭头函数
Func<int, int, int> add = (a, b) => a + b; // 有返回值 ≈ (a,b)=>a+b
Action<string> log = msg => Console.WriteLine(msg); // 无返回值 ≈ void 函数
// 事件(Secs4Net 里就是这样订阅设备消息的)
channel.ConnectionChanged += (sender, e) =>
{
Console.WriteLine($"连接状态: {e.Status}");
};
// += 订阅,-= 退订,语义和 JS 的 addEventListener 一致
10. 异常处理 ⭐
和 JS 几乎一样,只是多一个 finally 之外的 using:
try
{
await SendAsync(msg);
}
catch (SecsException ex) // catch 可以带类型过滤
{
logger.LogError(ex, "发送失败");
throw; // 重新抛出 ≈ JS throw
}
finally
{
// 清理,同 JS
}
// using:自动释放资源 ≈ JS 的 try { } finally { res.close() }
using var client = new TcpClient();
// 离开作用域自动调用 Dispose(),即使发生异常
11. 泛型
public class MessageQueue<T> where T : class // where 是约束
{
private readonly Queue<T> _queue = new();
public void Enqueue(T item) => _queue.Enqueue(item);
public T? Dequeue() => _queue.TryDequeue(out var item) ? item : null;
}
var q = new MessageQueue<string>(); // 用法 ≈ TS 泛型,一模一样
12. 项目组织 ⭐
// 每个文件通常这样开头(namespace ≈ 模块作用域,C# 10+ 可用 file-scoped)
namespace SecsGateway.Services;
public class GemService { /* ... */ }
// 用别人的类:文件顶部 using ≈ JS import
using Secs4Net;
using Microsoft.Extensions.Logging;
| JS/TS | C# |
|---|---|
npm / package.json |
NuGet / .csproj |
import x from 'y' |
using Y; |
export class A |
public class A(跨文件访问必须写 public) |
tsconfig.json |
.csproj |
| VS Code / WebStorm | Visual Studio / Rider / VS Code+C# 扩展 |
访问修饰符:public(公开)、private(默认,类内)、internal(程序集内)、protected。JS 里习惯不写修饰符,C# 里忘了写 public 会发现“别的类怎么访问不到”,这是新手最常踩的坑。
13. 实战:一个最小 Secs4Net 网关骨架 ⭐⭐⭐
把前面所有语法串起来(伪代码风格,展示 C# 写法味道):
using Microsoft.Extensions.Logging;
using Secs4Net;
namespace SecsGateway;
public record DeviceConfig(string Host, int Port, int DeviceId);
public class GemGateway
{
private readonly DeviceConfig _config; // readonly ≈ const
private readonly ILogger<GemGateway> _logger;
private readonly ConcurrentDictionary<int, byte[]> _traces = new();
private SecsMessage? _lastPrimary; // 可空引用类型
public event EventHandler<string>? AlarmRaised; // 事件声明,? 表示事件可为空
public GemGateway(DeviceConfig config, ILogger<GemGateway> logger)
{
_config = config;
_logger = logger;
}
public async Task<bool> EstablishCommunicationAsync(CancellationToken ct = default)
{
try
{
_logger.LogInformation("正在连接 {Host}:{Port}", _config.Host, _config.Port);
// 构造 S1F13 建立通信
var s1f13 = new SecsMessage(1, 13)
{
SecsItem = Item.L()
};
var s1f14 = await SendAsync(s1f13, ct); // await 设备回复
var accepted = s1f14.SecsItem.FirstOrDefault()?.GetValue<byte>() == 0;
return accepted;
}
catch (SecsException ex)
{
_logger.LogError(ex, "建立通信失败,设备 {DeviceId}", _config.DeviceId);
return false;
}
}
public async Task SubscribeAlarmsAsync(CancellationToken ct)
{
// S5F1 报警上报的处理:模式匹配解构消息
var s5f1 = _lastPrimary;
if (s5f1 is { Name: "AlarmReport" })
{
var alid = s5f1.SecsItem.Items[0].GetValue<int>();
var alcd = s5f1.SecsItem.Items[1].GetValue<byte>();
var text = s5f1.SecsItem.Items.Count > 2
? s5f1.SecsItem.Items[2].GetString()
: "";
AlarmRaised?.Invoke(this, $"{alcd switch { 128 => "SET", 0 => "CLEAR", _ => "?" }} [{alid}] {text}");
}
await Task.CompletedTask;
}
private Task<SecsMessage> SendAsync(SecsMessage msg, CancellationToken ct)
{
// 调 Secs4Net 的底层发送,略
return Task.FromResult(msg);
}
}
14. 给前端工程师的踩坑清单
- 忘写
public—— 类/方法默认是private,跨文件访问不到 ==比较字符串 —— C# 字符串==是值比较(和 JS 不一样,反而更省心)Count是属性不是方法 ——list.Count不是list.count()- 在 lock 里 await —— 编译错误,也是死锁来源,先取出数据再异步
async void—— 除了事件处理器外禁用,异常会直接崩进程- 没有
undefined—— 判空统一用??/is null - 整数除法 ——
5 / 2 == 2,不是 2.5!要用5 / 2.0 - 大小写敏感且习惯 PascalCase —— 方法名
ConnectAsync、属性DeviceId,和 JS 的 camelCase 不同
15. 推荐学习路径
- 本教程过一遍语法(1~2 天)
- 写个小 Demo:用
Task.Delay+ConcurrentDictionary做一个模拟设备状态轮询服务 - 官方文档 learn.microsoft.com/dotnet/csharp(质量极高)
- 读 Secs4Net 的 GitHub 示例,跑通 S1F13/S1F14 建立通信
- 结合 SEMI E5 (SECS-II)、E30 (GEM) 标准文档理解消息语义

浙公网安备 33010602011771号