方法参数中的C#指针?

Ste*_*nal 6 c# variables methods pointers

我希望从它内部直接修改方法之外的变量值.
指针是正确的,对吗?

怎么样?

LBu*_*kin 14

在c#中,您可以使用refout修饰符应用传递引用语义:

void Foo( ref string s, ref int x )
{
    s = "Hello World"; // caller sees the change to s
    x = 100;           // caller sees the change to x
}

// or, alternatively...

void Bar( out string s )
{
    s = "Hello World"; 
}
Run Code Online (Sandbox Code Playgroud)

这两者之间的区别在于out,调用者在调用方法时不必指定值,因为要求被调用的方法在退出之前指定一个值.

在C#中,"指针"只能用于不安全的代码.与在C或C++中一样,C#中的指针允许您引用变量或对象的位置.C#中的引用是不同的 - 您不应该将它们视为指针 - 它们旨在更加不透明,并提供一种"引用"变量或对象的方式,而不必暗示它们在内存中指示它的位置.

使用引用,您可以使用特殊关键字(out,ref)将别名传递给变量.这些只在方法调用的上下文中可用 - 编译器可以使用有关所指对象生命周期的信息来确保引用不会超过原始变量的别名.


Mar*_*ers 8

您可以使用方法参数关键字ref:

void modifyFoo(ref int foo)
{
    foo = 42;
}
Run Code Online (Sandbox Code Playgroud)

像这样打电话:

int myFoo = 0;
modifyFoo(ref myFoo);
Console.WriteLine(myFoo);
Run Code Online (Sandbox Code Playgroud)

结果:

42
Run Code Online (Sandbox Code Playgroud)

从文档:

方法参数上的ref方法参数关键字使方法引用传递给方法的同一变量.当控制传递回调用方法时,对方法中的参数所做的任何更改都将反映在该变量中.

要使用ref参数,必须将参数显式作为ref参数传递给方法.ref参数的值将传递给ref参数.