在以下上下文中,使用 ref 关键字:
方法的签名和调用
这将使参数的引用地址传递给方法(而不是其值)。
{
static void Main(string[] args)
{
string zfc = "我的";
LeiYinYong . FF ( ref zfc );
Console . WriteLine ( zfc ); // 返回“我的天啊!”
zfc = "你的";
LeiYinYong . FF ( zfc );
Console . WriteLine ( zfc ); // 返回“你的”
}
}
public class LeiYinYong
{
public static string FF ( ref string 引用参数 )
{
return ( 引用参数 += "天啊!" );
}
public static string FF ( string 引用参数 )
{
return ( 引用参数 += "上帝!" );
}
}
方法签名中按引用返回
在方法签名中,按引用将值返回给调用方。
{
static void Main(string[] args)
{
int x = 2 , y = 3 ;
Console . WriteLine ( LeiYinYong . FF ( ref x , ref y ) ); // 返回 3
Console . WriteLine ( LeiYinYong . FF ( x , y ) ); // 返回 3
}
}
public class LeiYinYong
{
public static ref int FF ( ref int 整数1 , ref int 整数2 )
{
if ( 整数1 > 整数2 )
return ref 整数1;
else
return ref 整数2;
}
public static int FF ( int 整数1 , int 整数2 )
{
if ( 整数1 > 整数2 )
return 整数1;
else
return 整数2;
}
}
声明 ref 变量
在局部变量的声明中,声明 reference 变量。
public void FFref ( int Zhs )
{
ref int Zhs别名 = ref Zhs;
}
作为 ref 表达式或运算符的一部分
作为 ref 条件表达式或 ref 赋值运算符的一部分。
public static ref int FF引用最大 ( ref int 整数1 , ref int 整数2 )
{
ref int Zhs返回值 = ref 整数1 > 整数2 ? ref 整数1 : ref 整数2;
return ref Zhs返回值;
}
声明 ref struct 及其字段
在 struct 声明中,声明 ref struct 及其字段。
public ref struct CustomRef
{
public ReadOnlySpan < int > Inputs;
public ReadOnlySpan < int > Outputs;
private ref int Zhs;
}
用于泛型类
在泛型类型声明中用于指定类型参数 allows ref struct 类型。
class Lei泛型引用结构 < T , S >
where T : allows ref struct
where S : T
{
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。