How do I convert a C# string to a Span? (Span)

前端 未结 2 2009
说谎
说谎 2021-01-07 17:05

How do I convert a string to a Span?

Span mySpan = \"My sample source string\";
2条回答
  •  盖世英雄少女心
    2021-01-07 17:39

    You need to install the System.Memory NuGet package.

    There are extension methods for strings called .AsSpan() or .AsReadOnlySpan() to convert a string to the appropriate Span.

    Example:

    Span mySpan = "My sample source string".AsSpan();
    ReadOnlySpan myReadOnlySpan = "My read only string".AsReadOnlySpan();
    

    Source: MSDN Channel 9 "C# 7.2: Understanding Span" (around the 6 minute mark)

    Update: this answer was correct at the time, but based on a preview version. See updated answer on this page by gfoidl for current procedure.

提交回复
热议问题