领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

C#与TypeScript语法深度对比

nixiaole 2025-04-27 15:32:08 知识剖析 8 ℃

1. 语言背景与定位

C#

  • 微软开发的面向对象编程语言
  • 主要用于.NET平台开发(桌面应用、Web后端、游戏开发等)
  • 强类型、静态类型语言
  • 编译为中间语言(IL)后在CLR上运行

TypeScript (TS)

  • 微软开发的JavaScript超集
  • 主要用于前端开发(可编译为纯JavaScript)
  • 静态类型系统(但运行时仍是动态的JavaScript)
  • 设计目标是解决JavaScript在大规模应用开发中的痛点

2. 基础类型对比

2.1 基本类型声明

C#:

int age = 30;
string name = "Alice";
bool isActive = true;
double price = 9.99;
decimal precise = 123.456m;

TypeScript:

let age: number = 30;
let name: string = "Alice";
let isActive: boolean = true;
let price: number = 9.99;
// TypeScript没有decimal类型,所有浮点都是number

2.2 类型推断

两者都支持类型推断:

C#:

var age = 30;  // 推断为int
var name = "Alice";  // 推断为string

TypeScript:

let age = 30;  // 推断为number
let name = "Alice";  // 推断为string

2.3 特殊类型

C#特有:

DateTime now = DateTime.Now;  // 日期时间类型
Guid id = Guid.NewGuid();     // 全局唯一标识符

TypeScript特有:

let maybe: string | null = null;  // 联合类型
let anything: any = "可以是任何类型";  // 任意类型
let unknownValue: unknown = "类型未知";  // 比any更安全的未知类型

3. 复杂类型与集合

3.1 数组

C#:

int[] numbers = {1, 2, 3};
List<string> names = new List<string> {"Alice", "Bob"};

TypeScript:

let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob"];  // 泛型语法

3.2 元组

C#:

// C# 7.0+ 支持元组
var person = (Name: "Alice", Age: 30);
Console.WriteLine(person.Name);

TypeScript:

let person: [string, number] = ["Alice", 30];
console.log(person[0]);  // 访问通过索引

3.3 对象/类

C#类:

public class Person {
    public string Name { get; set; }
    public int Age { get; set; }
    
    public Person(string name, int age) {
        Name = name;
        Age = age;
    }
    
    public void Greet() {
        Console.WriteLine(#34;Hello, I'm {Name}");
    }
}

TypeScript类:

class Person {
    name: string;
    age: number;
    
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
    
    greet(): void {
        console.log(`Hello, I'm ${this.name}`);
    }
}

3.4 接口

C#接口:

public interface IAnimal {
    string Name { get; }
    void MakeSound();
}

public class Dog : IAnimal {
    public string Name => "Dog";
    
    public void MakeSound() {
        Console.WriteLine("Woof!");
    }
}

TypeScript接口:

interface Animal {
    name: string;
    makeSound(): void;
}

class Dog implements Animal {
    name: string = "Dog";
    
    makeSound(): void {
        console.log("Woof!");
    }
}

4. 函数与Lambda表达式

4.1 函数声明

C#:

public int Add(int a, int b) {
    return a + b;
}

// 表达式体方法
public int Multiply(int a, int b) => a * b;

TypeScript:

function add(a: number, b: number): number {
    return a + b;
}

// 箭头函数
const multiply = (a: number, b: number): number => a * b;

4.2 可选参数与默认值

C#:

public void Greet(string name, string greeting = "Hello") {
    Console.WriteLine(#34;{greeting}, {name}!");
}

// 调用
Greet("Alice");  // 使用默认greeting
Greet("Bob", "Hi");  // 提供greeting

TypeScript:

function greet(name: string, greeting: string = "Hello"): void {
    console.log(`${greeting}, ${name}!`);
}

// 调用
greet("Alice");  // 使用默认greeting
greet("Bob", "Hi");  // 提供greeting

4.3 函数重载

C#:

public class Calculator {
    public int Add(int a, int b) => a + b;
    public double Add(double a, double b) => a + b;
    public string Add(string a, string b) => a + b;
}

TypeScript:

function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
    return a + b;
}

5. 异步编程

5.1 异步函数

C#:

public async Task<string> FetchDataAsync() {
    using var client = new HttpClient();
    return await client.GetStringAsync("https://example.com");
}

TypeScript:

async function fetchData(): Promise<string> {
    const response = await fetch('https://example.com');
    return await response.text();
}

5.2 Promise/Task对比

C# Task:

public Task<int> CalculateAsync() {
    return Task.Run(() => {
        Thread.Sleep(1000);
        return 42;
    });
}

TypeScript Promise:

function calculate(): Promise<number> {
    return new Promise(resolve => {
        setTimeout(() => resolve(42), 1000);
    });
}

6. 泛型

6.1 泛型函数

C#:

public T Identity<T>(T value) {
    return value;
}

var result = Identity<string>("hello");

TypeScript:

function identity<T>(value: T): T {
    return value;
}

const result = identity<string>("hello");

6.2 泛型约束

C#:

public interface IHasId {
    int Id { get; }
}

public T FindById<T>(IEnumerable<T> items, int id) where T : IHasId {
    return items.FirstOrDefault(item => item.Id == id);
}

TypeScript:

interface HasId {
    id: number;
}

function findById<T extends HasId>(items: T[], id: number): T | undefined {
    return items.find(item => item.id === id);
}

7. 枚举

C#枚举:

public enum Color {
    Red,
    Green,
    Blue
}

var favorite = Color.Blue;

TypeScript枚举:

enum Color {
    Red,
    Green,
    Blue
}

let favorite: Color = Color.Blue;

8. 模块与命名空间

C#命名空间:

namespace MyApp.Models {
    public class Person {
        // ...
    }
}

// 使用
using MyApp.Models;
var person = new Person();

TypeScript模块:

// person.ts
export class Person {
    // ...
}

// 使用
import { Person } from './person';
const person = new Person();

9. 装饰器与特性

C#特性(Attributes):

[Serializable]
public class Person {
    [Obsolete("Use FullName instead")]
    public string Name { get; set; }
}

TypeScript装饰器:

@serializable
class Person {
    @deprecated("Use fullName instead")
    name: string;
}

10. 空值处理

C#可空类型:

int? age = null;  // 可空整型
string name = null;  // 引用类型默认可为null

// C# 8.0+ 可空引用类型
#nullable enable
string notNullName = "Alice";
string? nullableName = null;

TypeScript:

let age: number | null = null;
let name: string | undefined = undefined;

// TypeScript 2.0+ 严格空检查
let notNullName: string = "Alice";
let nullableName: string | null = null;

11. 类型转换

C#类型转换:

object obj = "hello";
string str = (string)obj;  // 显式转换

if (obj is string s) {  // 模式匹配
    Console.WriteLine(s);
}

string anotherStr = obj as string;  // as运算符

TypeScript类型断言:

let obj: any = "hello";
let str = obj as string;  // 类型断言

if (typeof obj === "string") {  // 类型保护
    console.log(obj);
}

12. 总结对比表

特性

C#

TypeScript

类型系统

强类型,静态,编译时检查

静态类型系统,编译为动态JavaScript

平台

.NET运行时

编译为JavaScript,运行在浏览器/Node

类继承

单继承,多接口实现

单继承,多接口实现

接口

只能定义契约

还能定义对象形状

泛型

运行时保留

编译时擦除

异步

async/await基于Task

async/await基于Promise

模块系统

命名空间

ES模块/CommonJS

空值处理

可空值类型,可空引用类型

联合类型(null/undefined)

元编程

反射,特性

装饰器

类型推断

var关键字

自动类型推断

最近发表
标签列表