c#中ref的用法

该ref关键字使一个参数通过引用传递,而不是价值。通过引用传递的效果是被调用方法中的参数的任何改变反映在调用方法中。例如,如果调用者传递一个局部变量表达式或一个数组元素访问表达式,并且被调用的方法替换ref参数引用的对象,则调用者的局部变量或数组元素现在引用新对象。

 class RefExample
    {
        static void Method(ref int i)
        {
            // Rest the mouse pointer over i to verify that it is an int.
            // The following statement would cause a compiler error if i
            // were boxed as an object.
            i = i + 44;
        }

        static void Main()
        {
            int val = 1;
            Method(ref val);
            Console.WriteLine(val);

            // Output: 45
        }
    }

传递给一个参数ref传递之前,参数必须被初始化。这不同于out参数,其参数没有它们传递之前明确初始化。欲了解更多信息,请参阅出来。
一个类的成员不能有,只有不同的签名ref和out。如果一个类型的两个部件之间的唯一区别是,它们中的一个具有发生编译错误ref参数,而另一个具有一个out参数。以下代码,例如,不编译。
In other situations that require signature matching, such as hiding or overriding, ref and out are part of the signature and don’t match each other.
Properties are not variables. They are methods, and cannot be passed to ref parameters.
For information about how to pass arrays, see Passing Arrays Using ref and out.
You can’t use the ref and out keywords for the following kinds of methods:
Async methods, which you define by using the async modifier.
Iterator methods, which include a yield return or yield break statement.` class RefExample2
{
static void ChangeByReference(ref Product itemRef)
{
// The following line changes the address that is stored in
// parameter itemRef. Because itemRef is a ref parameter, the
// address that is stored in variable item in Main also is changed.
itemRef = new Product(“Stapler”, 99999);

        // You can change the value of one of the properties of
        // itemRef. The change happens to item in Main as well.
        itemRef.ItemID = 12345;
    }

    static void Main()
    {
        // Declare an instance of Product and display its initial values.
        Product item = new Product("Fasteners", 54321);
        System.Console.WriteLine("Original values in Main.  Name: {0}, ID: {1}\n",
            item.ItemName, item.ItemID);

        // Send item to ChangeByReference as a ref argument.
        ChangeByReference(ref item);
        System.Console.WriteLine("Back in Main.  Name: {0}, ID: {1}\n",
            item.ItemName, item.ItemID);
    }
}

class Product
{
    public Product(string name, int newID)
    {
        ItemName = name;
        ItemID = newID;
    }

    public string ItemName { get; set; }
    public int ItemID { get; set; }
}

`

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值