Setting a ref to a member field in C#

前端 未结 6 1899
悲哀的现实
悲哀的现实 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:21

    There are really two issues here.

    One, as the other posters have said, you can't strictly do what you're looking to do (as you may be able to with C and the like). However - the behavior and intent are still readily workable in C# - you just have to do it the C# way.

    The other issue is your unfortunate attempt to try and use strings - which are, as one of the other posters mentioned - immutable - and by definition get copied around.

    So, having said that, your code can easily be converted to this, which I think does do what you want:

    public class End
    {
        public StringBuilder parameter;
    
        public End(StringBuilder parameter)
        {
            this.parameter = parameter;
            this.Init();
            Console.WriteLine("Inside: {0}", parameter);
        }
    
        public void Init()
        {
            this.parameter.Clear();
            this.parameter.Append("success");
        }
    }
    
    class MainClass
    {
        public static void Main(string[] args)
        {
            StringBuilder s = new StringBuilder("failed");
            End e = new End(s);
            Console.WriteLine("After: {0}", s);
        }
    }
    

提交回复
热议问题