c# - 从多个切片创建 Span

标签 c# arrays .net-core

当前是否可以创建 Span<T> (和相关类型)基于另一个跨度的多个切片?

我想要实现的是一种多子字符串。

考虑以下字符数组:

[M][y][ ][b][r][i][l][l][i][a][n][t][ ][s][e][n][t][e][n][c][e]

我想根据范围列表组合一个新句子。

var newSentence = Span.MultiSlice(originalSentence, new List<(int start, int length)> { (3, 5), (13, 4) })

结果应该是ReadOnlySpan<char>代表brillsent .

还有可能组装这个Span通过从不同的跨度进行切片,而不仅仅是一个 originalSentence ,如上例所示?

最佳答案

不,这是定义:

https://learn.microsoft.com/en-us/dotnet/api/system.span-1?view=netcore-3.0

Provides a type- and memory-safe representation of a contiguous region of arbitrary memory.

您预期的用例中断 Span<T>的契约(Contract),因为您不代表单个连续的地址空间。

听起来你只是想要一个IEnumerable<Char>对一系列切片进行操作:

using OneOf; // https://github.com/mcintyre321/OneOf

using Run = OneOf<String,Span<Char>,IEnumerable<Char>>;

public class CompositeString
{
    private readonly List<Run> runs = new List<Run>();

    public void Add( String str ) => this.runs.Add( str );
    public void Add( Span<Char> span ) => this.runs.Add( span );
    public void Add( IEnumerable<Char> chars ) => this.runs.Add( chars ); 

    public void WriteTo( TextWriter wtr )
    {
        foreach( Run run in this.runs )
        {
            run.Switch(
                ( String s ) => wtr.Write( s ),
                ( Span<Char> span ) =>
                { // Span<T> doesn't implement IEnumerable<T>, but you can still use it with a `foreach`:
                    foreach( Char c in span ) wtr.Write( c );
                },
                ( IEnumerable<Char> chars ) =>
                {
                    foreach( Char c in chars ) wtr.Write( c );
                },
            );
        }
    }

    public override void ToString()
    {
        using( StringWriter wtr = new StringWriter() )
        {
            this.WriteTo( wtr );
            return wtr.ToString();
        }
    }
}

关于c# - 从多个切片创建 Span,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58599965/

相关文章:

c# - 在文本框更改时动态更新标签文本?

java - 我无法在 Selenium 中将 Java 的解决方案重写为 C#

javascript - 如何比较两个数组并从第一个数组中获取第一个匹配的对象?

javascript - 根据值对 Javascript 对象进行排序

arrays - 递归而不是循环

.net - 有一个 sln 文件,可以列出该 sln 下所有项目的所有文件吗?

c# 使用字符串参数定义在对象列表中过滤的属性

.net - Google Cloud 和 Google.Cloud.Functions.Framework

c# - 具有行和列标题WPF的ItemsControl

c# - 在 C# 中使文件可写的最佳方法