gpt4 book ai didi

c# - 将字符串转换为指针语法

转载 作者:太空狗 更新时间:2023-10-29 18:35:09 27 4
gpt4 key购买 nike

编译:

string s = "my string";
unsafe
{
fixed (char* ptr = s)
{
// do some works
}
}

这不是:

string s = "my string";
unsafe
{
fixed (char* ptr = (char*)s)
{
// do some works
}
}

error CS0030: Cannot convert type 'string' to 'char*'

我在 c# spec 中找不到位置它允许第一种语法但禁止第二种语法。你能帮忙指出这是在哪里谈论的吗?

最佳答案

它在规范的第 18.6 节中 - fixed 语句。

相关作品有:

fixed-statement:
  fixed ( pointer-type fixed-pointer-declarators ) embedded-statement

fixed-pointer-declarator:
   identifier = fixed-pointer-initializer

fixed-pointer-initializer:
  & variable-reference
  expression

您正在尝试使用表达式 版本。现在,虽然没有一个正常的“从stringchar *的表达式*转换,规范调用了 string 大小写,表示固定指针初始化器可以是:

An expression of type string, provided the type char* is implicitly convertible to the pointer type given in the fixed statement. In this case, the initializer computes the address of the first character in the string, and the entire string is guaranteed to remain at a fixed address for the duration of the fixed statement. The behavior of the fixed statement is implementation-defined if the string expression is null.

因此,虽然它看起来只是在执行普通变量声明并使用从stringchar * 的隐式转换,但您真正利用了 fixed-pointer-initializer 中允许的表达式的特殊情况。

关于c# - 将字符串转换为指针语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32769765/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com