ReadonlySpan 作为属性 [英] ReadonlySpan As Property

查看:12
本文介绍了ReadonlySpan 作为属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了解 .net core 3.0.据我所知,我不能使用 Span 或 ReadonlySpan 作为属性或成员,因为它是基于堆栈的结构.我想知道以下定义之间的区别.我可以成功定义part1"而没有任何错误.我收到以下第 2 部分的编译错误无法在此上下文中使用 Span 类型的 stackalloc 表达式的结果"对于第 3 部分,我收到了不同的编译错误.字段或自动实现的属性不能是 ReadonlySpan 类型"

I try to understand .net core 3.0. As far as i know, i cannot use Span or ReadonlySpan as properties or members since it is stack based struct. And I want to know the differences between the following definition. I can successfully define 'part1' without any error. I received the following compile error for part2 "A result of a stackalloc expression of type Span cannot be used in this context" For part3, i received the different compile error. "Field or auto-implemented property cannot be type ReadonlySpan"

public class KeyGenWithSpan
{
   private static ReadOnlySpan<char> part1 => new[] { 'p', '1'};
   private static ReadOnlySpan<char> part2 => stackalloc[]{'1','2'};
   private static ReadOnlySpan<char> part3 = stackalloc[]{'1','2'};
}

推荐答案

span 是一个基于堆栈的结构,但数据可以任何地方.它可以在数组中,可以是非托管内存,可以是堆栈,可以是固定缓冲区"或字符串等.

The span is a stack-based struct, but the data can be anywhere. It could be in an array, it could be unmanaged memory, it could be the stack, it could be a "fixed buffer", or a string, etc.

可以将跨度作为属性.您不能拥有的是作为字段的跨度,除了ref struct类型.该属性将充当代理从某物(可能是一个数组)获取范围.

You can have spans as properties. What you can't have is spans as fields, except on ref struct types. The property would act as a proxy to get the span from something (perhaps an array).

part1 中,您每次都分配一个新数组,但这不是必需的 - 可以更聪明地完成.

In part1, you're allocating a new array every time, but that isn't necessary - it can be done smarter.

然而,这对于 stackalloc 是不可能的,因为 stackalloc 会在属性 getter 的堆栈帧中分配,当它不再存在时你退出吸气剂.

This however, is not possible for stackalloc, since stackalloc would allocate in the property getter's stack-frame, which no longer exists when you exit the getter.

考虑:

private static readonly char[] s_data = { 'p', '1'};
public static ReadOnlySpan<char> Data => s_data; // perfectly valid conversion

<小时>

注意对于某些类型(特别是:不是char),编译器可以在这里做额外的巫术:


Note that for some types (notably: not char), the compiler can do extra voodoo here:

public static ReadOnlySpan<byte> Data2 => new byte[] { 0, 1 };

是否每次在getter中编译成一个新数组;相反,它直接从程序集元数据中提取:

does not compile to a new array each time in the getter; instead, it draws directly from the assembly metadata:

.method public hidebysig specialname static valuetype [System.Runtime]System.ReadOnlySpan`1<uint8> get_Data2() cil managed
{
    .maxstack 8
    L_0000: ldsflda int16 <PrivateImplementationDetails>::3F29546453678B855931C174A97D6C0894B8F546
    L_0005: ldc.i4.2 
    L_0006: newobj instance void [System.Runtime]System.ReadOnlySpan`1<uint8>::.ctor(void*, int32)
    L_000b: ret 
}

这篇关于ReadonlySpan 作为属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆