代码高亮功能测试

这篇文章用于测试博客的代码高亮功能,包含多种主流编程语言的代码示例。

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// JavaScript 示例:实现一个简单的计算器类
class Calculator {
constructor() {
this.result = 0;
}

add(num) {
this.result += num;
return this;
}

subtract(num) {
this.result -= num;
return this;
}

multiply(num) {
this.result *= num;
return this;
}

divide(num) {
if (num === 0) {
throw new Error('除数不能为零');
}
this.result /= num;
return this;
}

clear() {
this.result = 0;
return this;
}

getResult() {
return this.result;
}
}

// 使用计算器
const calc = new Calculator();
console.log(calc.add(10).multiply(2).subtract(5).getResult()); // 输出: 15

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Python 示例:实现一个简单的 Web 服务器
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
# 处理 GET 请求
if self.path == '/':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"<html><body><h1>简单的 Python Web 服务器</h1></body></html>")
elif self.path == '/api/data':
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
data = {
'message': 'Hello, World!',
'status': 'success',
'timestamp': '2026-01-04'
}
self.wfile.write(json.dumps(data).encode('utf-8'))
else:
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"<html><body><h1>404 - 页面未找到</h1></body></html>")

if __name__ == '__main__':
server_address = ('', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
print('服务器运行在 http://localhost:8000')
httpd.serve_forever()

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Java 示例:实现一个简单的链表
public class LinkedList {
private Node head;
private int size;

// 内部节点类
private static class Node {
int data;
Node next;

Node(int data) {
this.data = data;
this.next = null;
}
}

// 添加元素到链表末尾
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
size++;
}

// 在指定位置插入元素
public void insert(int index, int data) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("索引超出范围");
}
Node newNode = new Node(data);
if (index == 0) {
newNode.next = head;
head = newNode;
} else {
Node current = head;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
}
size++;
}

// 删除指定位置的元素
public void remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("索引超出范围");
}
if (index == 0) {
head = head.next;
} else {
Node current = head;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}
size--;
}

// 获取指定位置的元素
public int get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("索引超出范围");
}
Node current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current.data;
}

// 获取链表大小
public int size() {
return size;
}

// 打印链表元素
public void print() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}

public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(10);
list.add(20);
list.add(30);
list.print(); // 输出: 10 -> 20 -> 30 -> null
list.insert(1, 15);
list.print(); // 输出: 10 -> 15 -> 20 -> 30 -> null
list.remove(2);
list.print(); // 输出: 10 -> 15 -> 30 -> null
System.out.println("链表大小: " + list.size()); // 输出: 链表大小: 3
}
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// C++ 示例:实现一个简单的智能指针
#include <iostream>
#include <stdexcept>

template <typename T>
class SmartPointer {
private:
T* m_ptr;
int* m_refCount;

public:
// 构造函数
explicit SmartPointer(T* ptr = nullptr) : m_ptr(ptr), m_refCount(new int(1)) {
if (ptr == nullptr) {
*m_refCount = 0;
}
}

// 拷贝构造函数
SmartPointer(const SmartPointer<T>& other) : m_ptr(other.m_ptr), m_refCount(other.m_refCount) {
if (m_ptr != nullptr) {
(*m_refCount)++;
}
}

// 析构函数
~SmartPointer() {
release();
}

// 拷贝赋值运算符
SmartPointer<T>& operator=(const SmartPointer<T>& other) {
if (this != &other) {
release();
m_ptr = other.m_ptr;
m_refCount = other.m_refCount;
if (m_ptr != nullptr) {
(*m_refCount)++;
}
}
return *this;
}

// 解引用运算符
T& operator*() const {
if (m_ptr == nullptr) {
throw std::runtime_error("尝试解引用空指针");
}
return *m_ptr;
}

// 成员访问运算符
T* operator->() const {
if (m_ptr == nullptr) {
throw std::runtime_error("尝试访问空指针成员");
}
return m_ptr;
}

// 获取引用计数
int getRefCount() const {
return *m_refCount;
}

private:
// 释放资源
void release() {
if (m_ptr != nullptr) {
(*m_refCount)--;
if (*m_refCount == 0) {
delete m_ptr;
delete m_refCount;
}
}
}
};

// 测试智能指针
class TestClass {
public:
TestClass(int value) : m_value(value) {
std::cout << "TestClass 构造函数被调用,值: " << m_value << std::endl;
}

~TestClass() {
std::cout << "TestClass 析构函数被调用,值: " << m_value << std::endl;
}

void print() const {
std::cout << "TestClass::print() 被调用,值: " << m_value << std::endl;
}

private:
int m_value;
};

int main() {
try {
// 创建智能指针
SmartPointer<TestClass> ptr1(new TestClass(10));
std::cout << "ptr1 引用计数: " << ptr1.getRefCount() << std::endl;

// 拷贝智能指针
SmartPointer<TestClass> ptr2 = ptr1;
std::cout << "ptr1 引用计数: " << ptr1.getRefCount() << std::endl;
std::cout << "ptr2 引用计数: " << ptr2.getRefCount() << std::endl;

// 使用智能指针
ptr1->print();
(*ptr2).print();

// 离开作用域,智能指针会自动释放资源
} catch (const std::exception& e) {
std::cerr << "异常: " << e.what() << std::endl;
return 1;
}

return 0;
}

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
// C# 示例:实现一个简单的依赖注入容器
using System;
using System.Collections.Generic;
using System.Reflection;

namespace DependencyInjection
{
// 生命周期枚举
public enum Lifetime
{
Transient,
Singleton
}

// 服务描述符
public class ServiceDescriptor
{
public Type ServiceType { get; }
public Type ImplementationType { get; }
public Lifetime Lifetime { get; }
public object Implementation { get; set; }

public ServiceDescriptor(Type serviceType, Type implementationType, Lifetime lifetime)
{
ServiceType = serviceType;
ImplementationType = implementationType;
Lifetime = lifetime;
}
}

// 依赖注入容器
public class Container
{
private readonly Dictionary<Type, ServiceDescriptor> _services = new();

// 注册服务
public void Register<TService, TImplementation>(Lifetime lifetime = Lifetime.Transient)
{
_services[typeof(TService)] = new ServiceDescriptor(typeof(TService), typeof(TImplementation), lifetime);
}

// 注册单例实例
public void RegisterSingleton<TService>(TService instance)
{
_services[typeof(TService)] = new ServiceDescriptor(typeof(TService), typeof(TService), Lifetime.Singleton)
{
Implementation = instance
};
}

// 解析服务
public TService Resolve<TService>()
{
return (TService)Resolve(typeof(TService));
}

// 解析服务(内部实现)
private object Resolve(Type serviceType)
{
if (!_services.TryGetValue(serviceType, out var descriptor))
{
throw new Exception($"服务 {serviceType.Name} 未注册");
}

// 如果是单例且已有实例,直接返回
if (descriptor.Lifetime == Lifetime.Singleton && descriptor.Implementation != null)
{
return descriptor.Implementation;
}

// 创建实例
var implementation = CreateInstance(descriptor.ImplementationType);

// 如果是单例,保存实例
if (descriptor.Lifetime == Lifetime.Singleton)
{
descriptor.Implementation = implementation;
}

return implementation;
}

// 创建实例
private object CreateInstance(Type implementationType)
{
// 获取构造函数
var constructor = implementationType.GetConstructors()[0];
var parameters = constructor.GetParameters();

// 解析构造函数参数
var resolvedParameters = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
resolvedParameters[i] = Resolve(parameters[i].ParameterType);
}

// 创建实例
return constructor.Invoke(resolvedParameters);
}
}

// 测试服务
public interface ILogger
{
void Log(string message);
}

public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine($"[日志] {message}");
}
}

public interface IUserService
{
void RegisterUser(string username);
}

public class UserService : IUserService
{
private readonly ILogger _logger;

// 构造函数注入
public UserService(ILogger logger)
{
_logger = logger;
}

public void RegisterUser(string username)
{
_logger.Log($"用户 {username} 注册成功");
}
}

// 测试程序
class Program
{
static void Main(string[] args)
{
// 创建容器
var container = new Container();

// 注册服务
container.Register<ILogger, ConsoleLogger>(Lifetime.Singleton);
container.Register<IUserService, UserService>();

// 解析服务
var userService = container.Resolve<IUserService>();
userService.RegisterUser("张三");
userService.RegisterUser("李四");

Console.WriteLine("依赖注入测试完成");
}
}
}

Go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Go 示例:实现一个简单的 HTTP 客户端和服务器
package main

import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)

// 定义响应结构
type Response struct {
Message string `json:"message"`
Timestamp time.Time `json:"timestamp"`
}

// 处理根路径请求
func rootHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, "<html><body><h1>Go HTTP 服务器</h1><p>这是一个简单的 Go HTTP 服务器示例</p></body></html>")
}

// 处理 API 请求
func apiHandler(w http.ResponseWriter, r *http.Request) {
// 设置 CORS 头
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")

// 创建响应数据
response := Response{
Message: "Hello from Go API",
Timestamp: time.Now(),
}

// 编码为 JSON 并发送响应
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}

// 简单的 HTTP 客户端函数
func httpClientExample() {
// 创建 HTTP 客户端
client := &http.Client{
Timeout: 10 * time.Second,
}

// 发送 GET 请求
resp, err := client.Get("http://localhost:8080/api")
if err != nil {
fmt.Printf("HTTP 请求失败: %v\n", err)
return
}
defer resp.Body.Close()

// 读取响应体
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("读取响应失败: %v\n", err)
return
}

// 打印响应
fmt.Printf("HTTP 响应: %s\n", string(body))
}

func main() {
// 注册路由
http.HandleFunc("/", rootHandler)
http.HandleFunc("/api", apiHandler)

// 启动服务器(在 goroutine 中)
go func() {
fmt.Println("服务器启动在 http://localhost:8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
fmt.Printf("服务器启动失败: %v\n", err)
}
}()

// 等待服务器启动
time.Sleep(1 * time.Second)

// 运行 HTTP 客户端示例
httpClientExample()

// 保持程序运行
fmt.Println("按 Ctrl+C 停止服务器...")
select {}
}

Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# Ruby 示例:实现一个简单的博客系统
class BlogPost
attr_accessor :title, :content, :author, :published_at, :tags

def initialize(title, content, author, tags = [])
@title = title
@content = content
@author = author
@published_at = Time.now
@tags = tags
end

def to_s
"#{@title} by #{@author} - #{@published_at.strftime('%Y-%m-%d')}"
end

def add_tag(tag)
@tags << tag unless @tags.include?(tag)
end

def remove_tag(tag)
@tags.delete(tag)
end

def tag_list
@tags.join(', ')
end
end

class Blog
attr_reader :posts

def initialize
@posts = []
end

def add_post(post)
@posts << post
end

def find_posts_by_author(author)
@posts.select { |post| post.author == author }
end

def find_posts_by_tag(tag)
@posts.select { |post| post.tags.include?(tag) }
end

def latest_posts(limit = 5)
@posts.sort_by { |post| post.published_at }.reverse.take(limit)
end

def total_posts
@posts.length
end
end

# 测试博客系统
def test_blog
# 创建博客实例
my_blog = Blog.new

# 创建博客文章
post1 = BlogPost.new("Ruby 入门指南", "这是一篇关于 Ruby 编程语言的入门教程...", "张三", ["Ruby", "编程", "入门"])
post2 = BlogPost.new("Rails 开发最佳实践", "介绍 Rails 框架的开发最佳实践...", "李四", ["Rails", "Ruby", "Web 开发"])
post3 = BlogPost.new("Git 版本控制", "Git 是一个强大的版本控制系统...", "王五", ["Git", "版本控制", "开发工具"])

# 添加文章到博客
my_blog.add_post(post1)
my_blog.add_post(post2)
my_blog.add_post(post3)

# 测试功能
puts "博客共有 #{my_blog.total_posts} 篇文章\n"

puts "最新文章:"
my_blog.latest_posts.each do |post|
puts "- #{post}"
end

puts "\n查找 Ruby 相关文章:"
my_blog.find_posts_by_tag("Ruby").each do |post|
puts "- #{post.title} (#{post.tag_list})"
end

puts "\n查找张三的文章:"
my_blog.find_posts_by_author("张三").each do |post|
puts "- #{post.title}"
end

# 添加标签测试
post1.add_tag("教程")
puts "\n为第一篇文章添加 '教程' 标签后:"
puts "标签列表:#{post1.tag_list}"
end

# 运行测试
test_blog

PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
<?php
// PHP 示例:实现一个简单的 MVC 框架核心

// 路由类
class Router {
private $routes = [];

// 注册 GET 路由
public function get($path, $callback) {
$this->routes['GET'][$path] = $callback;
}

// 注册 POST 路由
public function post($path, $callback) {
$this->routes['POST'][$path] = $callback;
}

// 匹配路由
public function match($method, $path) {
if (isset($this->routes[$method][$path])) {
return $this->routes[$method][$path];
}
return null;
}

// 调度路由
public function dispatch($method, $path) {
$callback = $this->match($method, $path);
if ($callback) {
call_user_func($callback);
} else {
$this->notFound();
}
}

// 404 处理
private function notFound() {
http_response_code(404);
echo "<h1>404 Not Found</h1>";
echo "<p>请求的页面不存在</p>";
}
}

// 控制器基类
abstract class Controller {
// 渲染视图
protected function render($view, $data = []) {
extract($data);
include "views/{$view}.php";
}

// 重定向
protected function redirect($url) {
header("Location: {$url}");
exit;
}

// 返回 JSON 响应
protected function json($data) {
header('Content-Type: application/json');
echo json_encode($data);
exit;
}
}

// 示例控制器
class HomeController extends Controller {
public function index() {
$this->render('home', [
'title' => '首页',
'message' => '欢迎来到我的博客'
]);
}

public function about() {
$this->render('about', [
'title' => '关于我们'
]);
}

public function contact() {
$this->render('contact', [
'title' => '联系我们'
]);
}

public function api() {
$this->json([
'message' => 'API 响应',
'status' => 'success',
'timestamp' => date('Y-m-d H:i:s')
]);
}
}

// 示例模型
class User {
public static function getUsers() {
// 模拟从数据库获取用户数据
return [
['id' => 1, 'name' => '张三', 'email' => 'zhangsan@example.com'],
['id' => 2, 'name' => '李四', 'email' => 'lisi@example.com'],
['id' => 3, 'name' => '王五', 'email' => 'wangwu@example.com']
];
}

public static function getUserById($id) {
$users = self::getUsers();
foreach ($users as $user) {
if ($user['id'] == $id) {
return $user;
}
}
return null;
}
}

// 初始化路由
$router = new Router();
$homeController = new HomeController();

// 注册路由
$router->get('/', [$homeController, 'index']);
$router->get('/about', [$homeController, 'about']);
$router->get('/contact', [$homeController, 'contact']);
$router->get('/api', [$homeController, 'api']);

// 获取请求方法和路径
$method = $_SERVER['REQUEST_METHOD'];
$path = $_SERVER['REQUEST_URI'];

// 简单的路径处理(移除查询字符串)
$path = strtok($path, '?');

// 调度路由
$router->dispatch($method, $path);

// 示例视图文件(views/home.php)
// <!DOCTYPE html>
// <html>
// <head>
// <title><?php echo $title; ?></title>
// </head>
// <body>
// <h1><?php echo $title; ?></h1>
// <p><?php echo $message; ?></p>
// </body>
// </html>

Swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
// Swift 示例:实现一个简单的协议和扩展
import Foundation

// 定义可打印协议
protocol Printable {
var description: String { get }
func printDetails()
}

// 实现默认方法
extension Printable {
func printDetails() {
print(self.description)
}
}

// 定义形状协议
protocol Shape: Printable {
var area: Double { get }
var perimeter: Double { get }
}

// 实现矩形结构体
struct Rectangle: Shape {
var width: Double
var height: Double

// 计算属性:面积
var area: Double {
return width * height
}

// 计算属性:周长
var perimeter: Double {
return 2 * (width + height)
}

// 协议属性:描述
var description: String {
return "矩形 - 宽度: \(width), 高度: \(height), 面积: \(area), 周长: \(perimeter)"
}
}

// 实现圆形结构体
struct Circle: Shape {
var radius: Double

// 计算属性:面积
var area: Double {
return Double.pi * radius * radius
}

// 计算属性:周长
var perimeter: Double {
return 2 * Double.pi * radius
}

// 协议属性:描述
var description: String {
return "圆形 - 半径: \(radius), 面积: \(area), 周长: \(perimeter)"
}
}

// 实现三角形结构体
struct Triangle: Shape {
var side1: Double
var side2: Double
var side3: Double

// 计算属性:面积(使用海伦公式)
var area: Double {
let s = (side1 + side2 + side3) / 2
return sqrt(s * (s - side1) * (s - side2) * (s - side3))
}

// 计算属性:周长
var perimeter: Double {
return side1 + side2 + side3
}

// 协议属性:描述
var description: String {
return "三角形 - 三边: \(side1), \(side2), \(side3), 面积: \(area), 周长: \(perimeter)"
}
}

// 形状管理器类
class ShapeManager {
private var shapes: [Shape]

// 构造函数
init() {
shapes = []
}

// 添加形状
func addShape(_ shape: Shape) {
shapes.append(shape)
}

// 移除形状
func removeShape(at index: Int) {
guard index >= 0 && index < shapes.count else {
print("索引超出范围")
return
}
shapes.remove(at: index)
}

// 计算总面积
var totalArea: Double {
return shapes.reduce(0) { $0 + $1.area }
}

// 计算总周长
var totalPerimeter: Double {
return shapes.reduce(0) { $0 + $1.perimeter }
}

// 打印所有形状
func printAllShapes() {
print("\n所有形状:")
for (index, shape) in shapes.enumerated() {
print("\(index + 1). \(shape.description)")
}
print("\n总面积:\(totalArea)")
print("总周长:\(totalPerimeter)")
}

// 查找最大面积的形状
func findLargestAreaShape() -> Shape? {
return shapes.max { $0.area < $1.area }
}
}

// 测试代码
func testShapes() {
// 创建形状管理器
let shapeManager = ShapeManager()

// 创建形状
let rectangle = Rectangle(width: 5.0, height: 3.0)
let circle = Circle(radius: 4.0)
let triangle = Triangle(side1: 3.0, side2: 4.0, side3: 5.0)

// 添加形状到管理器
shapeManager.addShape(rectangle)
shapeManager.addShape(circle)
shapeManager.addShape(triangle)

// 打印单个形状
print("单个形状详情:")
rectangle.printDetails()
circle.printDetails()
triangle.printDetails()

// 打印所有形状
shapeManager.printAllShapes()

// 查找最大面积的形状
if let largestShape = shapeManager.findLargestAreaShape() {
print("\n最大面积的形状:")
largestShape.printDetails()
}

// 移除一个形状
shapeManager.removeShape(at: 0)
print("\n移除第一个形状后:")
shapeManager.printAllShapes()
}

// 运行测试
testShapes()

Kotlin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Kotlin 示例:实现一个简单的协程并发程序
import kotlinx.coroutines.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

// 日志工具函数
fun log(message: String) {
val time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))
val threadName = Thread.currentThread().name
println("[$time] [$threadName] $message")
}

// 模拟耗时操作
suspend fun performTask(taskId: Int, delayMs: Long): String {
log("开始执行任务 $taskId,延迟 ${delayMs}ms")
delay(delayMs) // 非阻塞延迟
log("完成任务 $taskId")
return "任务 $taskId 的结果"
}

// 测试并发任务
fun testConcurrentTasks() = runBlocking { // 主协程
log("主协程开始")

// 创建多个协程并行执行
val task1 = async { performTask(1, 1000) }
val task2 = async { performTask(2, 1500) }
val task3 = async { performTask(3, 500) }

log("所有任务已启动")

// 等待所有任务完成并获取结果
val result1 = task1.await()
val result2 = task2.await()
val result3 = task3.await()

log("所有任务已完成")
log("结果:$result1, $result2, $result3")

log("主协程结束")
}

// 测试协程作用域
fun testCoroutineScope() = runBlocking { // 主协程
log("主协程开始")

// 创建一个协程作用域
coroutineScope {
// 启动多个协程
launch { performTask(1, 1000) }
launch { performTask(2, 1500) }
launch { performTask(3, 500) }
log("协程作用域内的所有协程已启动")
}

log("协程作用域已完成")
log("主协程结束")
}

// 测试超时处理
fun testTimeout() = runBlocking { // 主协程
log("主协程开始")

try {
val result = withTimeout(1000) { // 设置超时时间为1秒
performTask(1, 1500) // 这个任务需要1.5秒
}
log("任务完成,结果:$result")
} catch (e: TimeoutCancellationException) {
log("任务超时:${e.message}")
}

log("主协程结束")
}

// 测试结构化并发
fun testStructuredConcurrency() = runBlocking { // 主协程
log("主协程开始")

// 结构化并发:使用 withContext 指定调度器
val result = withContext(Dispatchers.Default) { // 使用默认调度器(适合CPU密集型任务)
val task1 = async { performTask(1, 1000) }
val task2 = async { performTask(2, 1500) }
val task3 = async { performTask(3, 500) }

// 组合结果
"${task1.await()}, ${task2.await()}, ${task3.await()}"
}

log("结构化并发结果:$result")
log("主协程结束")
}

// 主函数
fun main() {
log("程序开始")

// 运行各个测试
println("\n=== 测试并发任务 ===")
testConcurrentTasks()

println("\n=== 测试协程作用域 ===")
testCoroutineScope()

println("\n=== 测试超时处理 ===")
testTimeout()

println("\n=== 测试结构化并发 ===")
testStructuredConcurrency()

log("程序结束")
}

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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// TypeScript 示例:实现一个类型安全的事件总线
class EventBus {
// 事件处理器映射
private eventHandlers: Map<string, Array<(data: any) => void>> = new Map();

// 订阅事件
subscribe<T>(event: string, handler: (data: T) => void): () => void {
if (!this.eventHandlers.has(event)) {
this.eventHandlers.set(event, []);
}

const handlers = this.eventHandlers.get(event)!;
handlers.push(handler as (data: any) => void);

// 返回取消订阅函数
return () => {
const index = handlers.indexOf(handler as (data: any) => void);
if (index > -1) {
handlers.splice(index, 1);
// 如果没有更多处理器,移除事件
if (handlers.length === 0) {
this.eventHandlers.delete(event);
}
}
};
}

// 发布事件
publish<T>(event: string, data: T): void {
const handlers = this.eventHandlers.get(event);
if (handlers) {
// 克隆处理器数组,防止在处理过程中修改数组
[...handlers].forEach(handler => {
try {
handler(data);
} catch (error) {
console.error(`处理事件 "${event}" 时发生错误:`, error);
}
});
}
}

// 获取事件数量
getEventCount(): number {
return this.eventHandlers.size;
}

// 获取特定事件的处理器数量
getHandlerCount(event: string): number {
return this.eventHandlers.get(event)?.length || 0;
}

// 清除所有事件
clear(): void {
this.eventHandlers.clear();
}
}

// 定义事件类型
interface UserRegisteredEvent {
userId: string;
username: string;
email: string;
timestamp: Date;
}

interface OrderPlacedEvent {
orderId: string;
userId: string;
total: number;
items: Array<{
productId: string;
quantity: number;
price: number;
}>;
timestamp: Date;
}

interface SystemErrorEvent {
errorId: string;
message: string;
stack?: string;
timestamp: Date;
}

// 测试事件总线
function testEventBus() {
const eventBus = new EventBus();
console.log("事件总线初始化完成");
console.log(`初始事件数量: ${eventBus.getEventCount()}`);

// 订阅用户注册事件
const unsubscribeUserRegistered = eventBus.subscribe<UserRegisteredEvent>("user.registered", (event) => {
console.log(`\n用户注册事件处理:`);
console.log(`- 用户ID: ${event.userId}`);
console.log(`- 用户名: ${event.username}`);
console.log(`- 邮箱: ${event.email}`);
console.log(`- 时间: ${event.timestamp.toISOString()}`);
});

// 订阅订单事件(多个处理器)
const unsubscribeOrderPlaced1 = eventBus.subscribe<OrderPlacedEvent>("order.placed", (event) => {
console.log(`\n订单事件处理器1:`);
console.log(`- 订单ID: ${event.orderId}`);
console.log(`- 用户ID: ${event.userId}`);
console.log(`- 总金额: ${event.total}`);
console.log(`- 商品数量: ${event.items.length}`);
});

const unsubscribeOrderPlaced2 = eventBus.subscribe<OrderPlacedEvent>("order.placed", (event) => {
console.log(`\n订单事件处理器2:`);
const totalItems = event.items.reduce((sum, item) => sum + item.quantity, 0);
console.log(`- 订单ID: ${event.orderId}`);
console.log(`- 商品总数量: ${totalItems}`);
});

// 订阅系统错误事件
const unsubscribeSystemError = eventBus.subscribe<SystemErrorEvent>("system.error", (event) => {
console.error(`\n系统错误事件:`);
console.error(`- 错误ID: ${event.errorId}`);
console.error(`- 错误信息: ${event.message}`);
if (event.stack) {
console.error(`- 堆栈跟踪: ${event.stack}`);
}
});

console.log(`\n订阅后事件数量: ${eventBus.getEventCount()}`);
console.log(`订单事件处理器数量: ${eventBus.getHandlerCount("order.placed")}`);

// 发布事件
console.log(`\n=== 发布事件 ===`);

// 发布用户注册事件
eventBus.publish<UserRegisteredEvent>("user.registered", {
userId: "user-001",
username: "testuser",
email: "test@example.com",
timestamp: new Date()
});

// 发布订单事件
eventBus.publish<OrderPlacedEvent>("order.placed", {
orderId: "order-001",
userId: "user-001",
total: 199.99,
items: [
{ productId: "prod-001", quantity: 2, price: 49.99 },
{ productId: "prod-002", quantity: 1, price: 99.99 }
],
timestamp: new Date()
});

// 发布系统错误事件
eventBus.publish<SystemErrorEvent>("system.error", {
errorId: "error-001",
message: "数据库连接失败",
stack: "Error: 数据库连接失败\n at Database.connect (db.js:42:15)\n at App.start (app.js:23:10)",
timestamp: new Date()
});

// 取消一个订单事件订阅
console.log(`\n=== 取消一个订单事件订阅 ===`);
unsubscribeOrderPlaced1();
console.log(`订单事件处理器数量: ${eventBus.getHandlerCount("order.placed")}`);

// 再次发布订单事件,验证只有一个处理器执行
eventBus.publish<OrderPlacedEvent>("order.placed", {
orderId: "order-002",
userId: "user-002",
total: 89.99,
items: [
{ productId: "prod-003", quantity: 1, price: 89.99 }
],
timestamp: new Date()
});

// 清除所有事件
console.log(`\n=== 清除所有事件 ===`);
eventBus.clear();
console.log(`清除后事件数量: ${eventBus.getEventCount()}`);

// 验证事件已清除
eventBus.publish<UserRegisteredEvent>("user.registered", {
userId: "user-003",
username: "testuser2",
email: "test2@example.com",
timestamp: new Date()
});
console.log("发布事件后没有处理器执行,验证清除成功");
}

// 运行测试
testEventBus();

Rust

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// Rust 示例:实现一个简单的命令行参数解析器
use std::env;
use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;

// 错误类型
#[derive(Debug)]
enum ParseError {
InvalidArgument(String),
MissingValue(String),
UnknownArgument(String),
}

impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::InvalidArgument(arg) => write!(f, "无效参数: {}", arg),
ParseError::MissingValue(arg) => write!(f, "参数 {} 缺少值", arg),
ParseError::UnknownArgument(arg) => write!(f, "未知参数: {}", arg),
}
}
}

impl std::error::Error for ParseError {}

// 命令行参数解析器
struct ArgParser {
args: Vec<String>,
index: usize,
options: HashMap<String, Option<String>>,
flags: Vec<String>,
}

impl ArgParser {
// 创建新的解析器
fn new(args: Vec<String>) -> Self {
Self {
args,
index: 1, // 跳过程序名
options: HashMap::new(),
flags: Vec::new(),
}
}

// 解析参数
fn parse(&mut self) -> Result<(), Box<dyn std::error::Error>> {
while self.index < self.args.len() {
let arg = &self.args[self.index];
self.index += 1;

if arg.starts_with("--") {
// 长选项,如 --help, --output=file.txt
self.parse_long_option(arg)?;
} else if arg.starts_with("-") && arg.len() > 1 {
// 短选项,如 -h, -o file.txt
self.parse_short_option(arg)?;
} else {
// 位置参数(本例中暂时忽略)
continue;
}
}
Ok(())
}

// 解析长选项
fn parse_long_option(&mut self, arg: &str) -> Result<(), Box<dyn std::error::Error>> {
let arg = arg.strip_prefix("--").unwrap();

if let Some((name, value)) = arg.split_once('=') {
// 带值的长选项,如 --output=file.txt
self.options.insert(name.to_string(), Some(value.to_string()));
} else {
// 不带值的长选项,检查下一个参数是否是值
if self.index < self.args.len() {
let next_arg = &self.args[self.index];
if !next_arg.starts_with("-") {
// 下一个参数是值
self.options.insert(arg.to_string(), Some(next_arg.to_string()));
self.index += 1;
} else {
// 没有值,视为标志
self.flags.push(arg.to_string());
}
} else {
// 没有下一个参数,视为标志
self.flags.push(arg.to_string());
}
}
Ok(())
}

// 解析短选项
fn parse_short_option(&mut self, arg: &str) -> Result<(), Box<dyn std::error::Error>> {
let arg = arg.strip_prefix("-").unwrap();

for (i, c) in arg.chars().enumerate() {
let flag = c.to_string();

// 检查是否是最后一个字符且有值
if i == arg.len() - 1 && self.index < self.args.len() {
let next_arg = &self.args[self.index];
if !next_arg.starts_with("-") {
// 下一个参数是值
self.options.insert(flag, Some(next_arg.to_string()));
self.index += 1;
continue;
}
}

// 没有值,视为标志
self.flags.push(flag);
}
Ok(())
}

// 获取选项值
fn get_option<T: FromStr>(&self, name: &str) -> Option<Result<T, T::Err>> {
self.options.get(name).map(|opt| {
opt.as_ref().unwrap().parse()
})
}

// 检查标志是否存在
fn has_flag(&self, name: &str) -> bool {
self.flags.contains(&name.to_string()) ||
self.options.contains_key(name)
}

// 获取所有选项
fn get_options(&self) -> &HashMap<String, Option<String>> {
&self.options
}

// 获取所有标志
fn get_flags(&self) -> &Vec<String> {
&self.flags
}
}

// 示例:使用参数解析器
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = env::args().collect();
let mut parser = ArgParser::new(args);

// 解析参数
parser.parse()?;

// 显示解析结果
println!("解析结果:");
println!("选项: {:?}", parser.get_options());
println!("标志: {:?}", parser.get_flags());

// 检查特定标志
if parser.has_flag("h") || parser.has_flag("help") {
println!("\n帮助信息:");
println!(" -h, --help 显示帮助信息");
println!(" -v, --version 显示版本信息");
println!(" -o, --output 指定输出文件");
println!(" -l, --level 设置日志级别");
return Ok(());
}

if parser.has_flag("v") || parser.has_flag("version") {
println!("\n版本: 1.0.0");
return Ok(());
}

// 获取选项值
if let Some(level_result) = parser.get_option::<u32>("l") {
match level_result {
Ok(level) => println!("\n日志级别: {}", level),
Err(e) => eprintln!("无效的日志级别: {:?}", e),
}
}

if let Some(output_result) = parser.get_option::<String>("o") {
match output_result {
Ok(output) => println!("输出文件: {}", output),
Err(e) => eprintln!("无效的输出文件: {:?}", e),
}
}

println!("\n程序执行完成");
Ok(())
}

总结

这篇文章测试了博客的代码高亮功能,包含了12种主流编程语言的代码示例,每种语言都有一定长度的代码,展示了不同的代码结构和语法特性。

测试的编程语言包括:

  1. JavaScript
  2. Python
  3. Java
  4. C++
  5. C#
  6. Go
  7. Ruby
  8. PHP
  9. Swift
  10. Kotlin
  11. TypeScript
  12. Rust

通过这篇测试文章,可以验证博客系统对不同编程语言代码高亮的支持情况。