Setting a ref to a member field in C#

前端 未结 6 1897
悲哀的现实
悲哀的现实 2021-02-08 13:32

I\'d like to assign a reference to a member field. But I obviously do not understand this part of C# very well, because I failed :-) So, here\'s my code:

public          


        
6条回答
  •  失恋的感觉
    2021-02-08 14:09

    As others have pointed out, you cannot store a reference to a variable in a field in C#, or indeed, any CLR language.

    Of course you can capture a reference to a class instance that contains a variable easily enough:

    sealed class MyRef
    {
      public T Value { get; set; }
    }
    public class End 
    {
      public MyRef parameter;
      public End(MyRef parameter) 
      {
        this.parameter = parameter;
        this.Init();
        Console.WriteLine("Inside: {0}", parameter.Value);
      }
      public void Init() 
      {
        this.parameter.Value = "success";
      }
    }
    class MainClass 
    {
      public static void Main() 
      {
        MyRef s = new MyRef();
        s.Value = "failed";
        End e = new End(s);
        Console.WriteLine("After: {0}", s.Value);
      }
    }
    

    Easy peasy.

提交回复
热议问题