浩明-空间 浩明-空间
首页
  • Unity

    • 类比法学c#
  • 学习笔记

    • 《JavaScript高级程序设计》
    • 《TypeScript 从零实现 axios》
    • TypeScript
    • JS设计模式总结
  • typescript杂谈

    • 为什么要用ts
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • vim学习
  • webgl基础
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 悟道
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

储浩明

热爱编程的小明
首页
  • Unity

    • 类比法学c#
  • 学习笔记

    • 《JavaScript高级程序设计》
    • 《TypeScript 从零实现 axios》
    • TypeScript
    • JS设计模式总结
  • typescript杂谈

    • 为什么要用ts
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • vim学习
  • webgl基础
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 悟道
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • JavaScript文章

  • Unity

    • C#类比学习
    • ts-c#的泛型
      • ts-c#的泛型
        • TypeScript中,定义一个泛型函数
        • C#中定义一个泛型函数
        • typeScript定义泛型类
        • C#中定义一个泛型类
    • c#命名空间与es6模块
    • lambda表达式
    • c#和ts的异步编程
    • C#与ts的数组操作方法
    • c#与ts事件
    • c#和ts的继承
    • c#与ts接口
    • c#与ts类对象
  • 学习笔记

  • typescript杂谈

  • 前端
  • Unity
chuhaoming
2024-08-03
目录

ts-c#的泛型

# ts-c#的泛型

C#和TypeScript都支持泛型编程,这有助于编写可重用和类型安全的代码。

# TypeScript中,定义一个泛型函数


function identity<T>(arg: T): T {
    return arg;
}
// 这里的<T>表示这是一个泛型函数,T是一个类型参数,它可以在使用时指定具体的类型。我们可以这样调用该函数:
let output = identity<string>("myString"); // 类型为 string
let output = identity<number>(100); // 类型为 number

1
2
3
4
5
6
7
8

# C#中定义一个泛型函数


public T Identity<T>(T arg)
{
    return arg;
}
//使用时也是类似的:
string output = Identity<string>("myString");
int output = Identity<int>(100);
1
2
3
4
5
6
7
8

# typeScript定义泛型类

class GenericList<T> {
  private items: T[] = [];

  add(item: T): void {
    this.items.push(item);
  }

  get(index: number): T {
    return this.items[index];
  }
}
//我们可以这样使用这个泛型类:
// 创建一个字符串列表
const strList = new GenericList<string>();
strList.add("Hello");
strList.add("World");
console.log(strList.get(0)); // 输出 "Hello"

// 创建一个数字列表
const numList = new GenericList<number>();
numList.add(1);
numList.add(2);
console.log(numList.get(1)); // 输出 2
//正如你所看到的,我们可以分别实例化 GenericList<string> 和 GenericList<number>来创建字符串列表和数字列表。TypeScript的类型系统会根据我们指定的类型参数,自动推断出方法参数和返回值的类型。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# C#中定义一个泛型类

using System.Collections.Generic;
public class GenericList<T>
{
 private List<T> items = new List<T>();
 public void add(T item)
 {
  items.Add(item);

 }
 public T get(int index)
 {
  return items[index];
 }

}

GenericList<string> numlist = new GenericList<string>();
numlist.add("chuhaoming");
numlist.get(0);// 输出 chuhaoming
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
编辑 (opens new window)
#C#
上次更新: 2024/08/09, 10:55:31
C#类比学习
c#命名空间与es6模块

← C#类比学习 c#命名空间与es6模块→

最近更新
01
c#与ts类对象
08-06
02
c#与ts接口
08-06
03
c#和ts的继承
08-06
更多文章>
Theme by Vdoing | Copyright © 2019-2024 Haoming chu | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式