Access variable from another method in another class

前端 未结 7 1388
闹比i
闹比i 2020-12-12 06:27

Suppose I have a file ABC.CS in that file I have a class ABC as below and method Test():

public class ABC
{
   public          


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 06:59

    The other answers I've seen so far are giving what I would consider extremely bad advice.

    Without more a more focused example, it's hard to say what the best approach would be. In general, you want to avoid your methods having side effects -- it makes it harder to debug and test your application. Basically, if you call the method 100 times with the same inputs, it should return the same results 100 times.

    In general, a good approach is to have your methods return something that represents the results of the operation it's performing.

    So, you have a class or struct that represents your return values:

    public struct SomeMethodResult
    {
        public int WhateverProperty {get;set;}
        public int WhateverOtherProperty {get;set;}
    }
    

    And then return an instance of that class as necessary:

    public SomeMethodResult SomeMethod()
    {
       var result = new SomeMethodResult();
       result.WhateverProperty = 1;
       result.WhateverOtherProperty = 2;
       //etc
       return result;
    }
    

提交回复
热议问题