SW 随笔 001 — InlineArray 带你飞(Since C#12)

声明:个人笔记,概不负责

开篇放水

这几天与 Copilot 对话,被种草了一个 InlineArray C# 特性,一个符合 native 思维的 数组 表达。

这东西还是 safe 的,啊,啊,真香 ......... 太香了!

进一步资料

// C# 12 - .NET 8 (2023-11)

设计:https://github.com/dotnet/runtime/blob/main/docs/design/features/InlineArrayAttribute.md

手册:https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.inlinearrayattribute

==

说实话,当年我是看到文档的,实在不知道这东西在干嘛,不懂的太多没办法,所以略过了。
现在的语言 3 年过后,就有很多新东西;5 年过后,就大变样;10 年过后,就得当一门新语言来学。

这是好事,许多年前,语言就像死了一样,发明过后没啥 的变化。
简单的讲 Morden C# 已经越来越像 C++ ; 而 Morden C++ 也越来越像 C#

2018 年 C# 7.2 (.NET Core 2.1) 引入 Span 后,这 C# 就开始往 native 的路上放飞自我了 ......

2020 年 C++20 引入 module 后,这 C++ 体质、物种都变了,原来是 像农业国家,现在像 工业国家 ......

千年不变的是 C 语言,这是好事,这东西变化太多,许多工业基础就得废。整个计算机行业,都得崩塌。
现在有了 AI 学点新东西,简直是 指数级 省时间!
可能,缩短 两个数量级 的时间,以上!
我是无意间和 Copilot 会话时,带出 旧代码的 使用部分,这东西猜到了我的实现,然后推荐了个更好的

代码就一句话

现在的代码

cs 复制代码
/// <summary>
/// A simple helper to map a null-terminated C string to a C# string
/// </summary>
[InlineArray(64)] // C# 12 - .NET 8  (2023-11)
public struct AsciiBytes64
{
    private byte Buffer;

    public static implicit operator string(AsciiBytes64 s) => s[..].AsciiBytesToString();

    public override string ToString() => this[..].AsciiBytesToString();
}

之前的代码

cs 复制代码
/// <summary>
/// A simple helper to map a null-terminated C string to a C# string
/// </summary>
public unsafe struct NullTerminatedString
{
    // hard-coded size since C# generic does not support const arg
    //
    private fixed byte Buffer[64];

    public static implicit operator string(NullTerminatedString s)
    {
        string str = new string((sbyte*)s.Buffer);
        return str;
    }

    public override string ToString()
    {
        return this;
    }
}

===没有啦,结束了