代码之家  ›  专栏  ›  技术社区  ›  Sandeep Pathak

通过引用返回c#?[副本]

c#
  •  2
  • Sandeep Pathak  · 技术社区  · 15 年前

    如何使用功能。请为我提供完整的函数定义 它在c#中通过引用返回。还有其他方法传递引用吗?请帮忙。

    4 回复  |  直到 15 年前
        1
  •  5
  •   Skurmedel    15 年前

    C#将事物分为引用类型和值类型。引用类型正如您所想象的,是通过引用传递的。这意味着传递对对象的引用。

    class MyClass // <- Reference type.
    {
       private MyClass _child = new MyClass();
    
       public MyClass GetChild()
       {
          return _child;
       }
    }
    

    值类型是通过值传递的;尽管我认为在引擎盖下可能会发生其他事情。不过,这对你来说并不重要,重要的只是行为。

    值类型示例: int , char Color ...

    通过创建引用类型 class ,以及通过 struct

        2
  •  5
  •   dtb    15 年前

    这是一个按值返回对象引用的方法:

    string Foo()
    {
        return "Hello";
    }
    
    string f = Foo();
    //  f == "Hello"
    

    void Bar(ref string s)
    {
        s = "Hello";
    }
    
    string f = null;
    Bar(ref f);
    //  f == "Hello"
    

    Parameter passing in C#

        3
  •  4
  •   Hans Passant    15 年前

    返回引用是一个C++术语。演示语法的示例:

    class Array {                  // This is C++ code
     public:
       int size() const;
       float& operator[] (int index);
       ...
     };
    
     int main()
     {
       Array a;
       for (int i = 0; i < a.size(); ++i)
         a[i] = 7;    // This line invokes Array::operator[](int)
       ...
     } 
    

    C#没有这个功能,它与垃圾收集器的概念非常不兼容。C++通过实际返回一个指针在引擎罩上实现这个。当垃圾收集器移动底层内部数组时,指针就失效了。

    这不是一个很大的问题,因为对象的变量已经是托管代码中的真实引用,就像引用的C++概念一样。但是 值类型,它们被复制。在这个特定的示例中,您将使用索引器:

    class Array<T> {            // This is C# code
        private T[] storage;
        public T this[int index] {
            get { return storage[index]; }
            set { storage[index] = value; }
        }
        // etc...        
    }
    
        4
  •  3
  •   RhysC    15 年前

    如果从函数返回一个引用类型,那么对象就被引用了。 CLR via C#