当前是否可以创建 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/