c#中ref的用法

来源:互联网 发布:广联达计价软件培训 编辑:程序博客网 时间:2024/05/22 07:08

该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; }}

`

0 0
原创粉丝点击