标签: ref-struct

如何使用xUnit测试ref struct方法是否抛出异常?

我是xUnit的新手,但据我所知,检查是否抛出异常的标准方法是使用Assert.Throws<T>Assert.ThrowsAny<T>方法.

但是这些方法期望将Action作为参数; 并且ref结构不能"嵌入"lambda中.

那么,如何测试ref struct的给定方法是否抛出?不起作用的代码示例:

[Fact]
public void HelpMe() {
    var pls = new Span<byte>();
    Assert.ThrowsAny<Exception>(() => {
        plsExplode = pls[-1];
    });
}
Run Code Online (Sandbox Code Playgroud)

c# xunit ref-struct

9
推荐指数
1
解决办法
64
查看次数

为什么ref结构不能用作类型参数?

C#7.2 介绍了 ref struct s.但是,考虑到ref struct这样的:

public ref struct Foo {
  public int Bar;
}
Run Code Online (Sandbox Code Playgroud)

我不能将它用作类型参数:

int i = 0;
var x = Unsafe.As<int, Foo>(ref i); // <- Error CS0306 The type 'Foo' may not be used as a type argument.
Run Code Online (Sandbox Code Playgroud)

我知道ref结构只能存在于堆栈中,而不能存在于堆中.但是,如果使用这种引用结构的泛型方法保证永远不会将它们放在堆上,如上面使用System.Runtime.CompilerServices.Unsafe包的示例,该怎么办?为什么我不能在这些情况下使用它们作为类型参数?

c# ref-struct c#-7.2

8
推荐指数
1
解决办法
561
查看次数

为什么“stackalloc”表达式不能分配给“Span&lt;T&gt;”参数?

考虑以下方法(fiddle):

void test(Span<int> param)
{
    //Fail, the stackalloc'ed buffer could be exposed.
    param = stackalloc int[10];
}

void test2(Span<int> param)
{
    //OK
    Span<int> local = stackalloc int[10];
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么param = stackalloc int[10];会产生错误:

“Span”类型表达式的结果stackalloc不能在此上下文中使用,因为它可能会暴露在包含方法之外

Span是一个ref struct但是(尽管有它的名字)它仍然是一个值类型,因此任何修改都param不会反映在调用者对象上。

我认为它param是一个具有初始值的局部变量,我不明白为什么test2可以编译,而test不能编译。

stackalloc int[10]in的返回值如何test逃逸方法的范围?

c# lifetime stackalloc ref-struct

5
推荐指数
1
解决办法
637
查看次数

在垃圾收集时,NodeJS中的内容会损坏ref-struct

ref-struct实例嵌套在另一个实例中,嵌套对象的其中一个属性在手动垃圾回收时会损坏.

请参阅此最小代码复制:https://github.com/hunterlester/minimum-ref-struct-corruption

请注意日志输出的第3行,其值name未损坏:

Running garbage collection...
authGranted object afte gc:  { name: '?_n9a\u0002', 'ref.buffer': <Buffer@0x00000261396F3910 18 86 6c 39 61 02 00 00> }
Unnested access container entry after gc:  { name: 'apps/net.maidsafe.examples.mailtutorial', 'ref.buffer': <Buffer@0x00000261396F3B10 60 68 6e 39 61 02 00 00> }
Globally assigned values after gc:  apps/net.maidsafe.examples.mailtutorial  _publicNames
Run Code Online (Sandbox Code Playgroud)

garbage-collection ref node.js ref-struct

4
推荐指数
1
解决办法
167
查看次数

为什么我可以在 c#7.3 中将 ref 结构声明为类的成员?

根据文档

不能将 ref 结构声明为类或普通结构的成员。

但我成功地编译并运行了这个:

public ref struct RefStruct
{
    public int value;
}
public class MyClass
{
    public RefStruct Item => default;
}    
...       

MyClass c = new MyClass();
Console.WriteLine(c.Item.value);
Run Code Online (Sandbox Code Playgroud)

现在RefStruct是 aref struct并且它是一个类的成员。这种说法在某些情况下是错误的吗?

更新 现在文档已更新为更准确的描述。

.net c# struct ref-struct c#-7.3

4
推荐指数
1
解决办法
2362
查看次数