How can i pass/use private variables froma class in Form1 with a public function?

前端 未结 5 752
粉色の甜心
粉色の甜心 2021-01-27 05:28

I don\'t want to make a new instance of Form1 in the class, and i dont want to use static.

I have these two variables which are private in the top of the cl

相关标签:
5条回答
  • 2021-01-27 05:42

    I don't know if I understand what you need.
    Anyway, you could try to use a public property:

    public List<float> PointX { get { return Point_X; } }
    public List<float> PointY { get { return Point_Y; } }
    
    0 讨论(0)
  • 2021-01-27 05:54

    You can not use private fields of a class inside another (cause Form is just another class). What you can do, if limiting the accessibility is important to you, is using internal keyword, instead of private. But it will work only if both classes are in the same assembly.

    internal List<float> Point_X = new List<float>();
    internal List<float> Point_Y = new List<float>();
    

    To be clear it's always a good to have some property or method that "wraps" access to the private fields, but as much as I understood it's not something you want to avoid, for some reason.

    0 讨论(0)
  • 2021-01-27 05:55

    There are two solutions to this:

    1. Make the variables public properties - though there are issues around the use of lists so having a ReadOnlyCollection wrapper is the way to solve this.

    2. Create a public method that performs the required manipulations on the lists.

    For example to add a point to the list you'd have:

    public void AddValueToX(float value)
    {
        PointX.Add(value);
    }
    

    If you wanted to test whether a value was in the list (which is fraught with danger as you are dealing with single precision values):

    public bool InListX(float value)
    {
        // A test on value vs the data in Point_X allowing for floating point inaccuracies
    }
    
    0 讨论(0)
  • 2021-01-27 05:56

    Try this:

    public ReadOnlyCollection<float> GetXValues()
    {
        return Point_X.AsReadOnly();
    }
    

    If I understand, you want to give read-only access to Point_X outside of the class. This method will allow you to do that. Or you could use a read-only property:

    public ReadOnlyCollection<float> XValues
    {
        get
        {
            return Point_X.AsReadOnly();
        }
    }
    

    The key thing is the AsReadOnly method call to prevent changes to the collection outside of the class. If you return the List<T> directly, it can be changed by the caller.

    0 讨论(0)
  • 2021-01-27 06:05

    The canonical solution is

    private List<float> mPoint_X = new List<float>();
    private List<float> mPoint_Y = new List<float>();
    
    public List<float> Point_X { get { return mPoint_X; } }
    public List<float> Point_Y { get { return mPoint_Y; } }
    
    0 讨论(0)
提交回复
热议问题