简体   繁体   中英

C# library in dll and static variable problem

I want to make a library in.dll so it can be reused. The user who uses the library should be able to say what is the number of colors to track, and I've put this data in varaible 'num' which has to be static if I want to use it the way I want.

    static int num = 2;     
    TrackColorRange[] trackingColorRanges = new TrackColorRange[num]; ... 
    PictureBox[] ShowPointLocations = new PictureBox[num];   

Now it's not the problem if the user uses the code directly, but if I put it in a.dll the user can't change the value of num. What would be the solution for this problem? Thank you.

I would refactor your design and make this an optional constructor parameter for your class, initialize your instance variables in the constructor then:

class Foo
{
    TrackColorRange[] trackingColorRanges;
    PictureBox[] showPointLocations;

    public Foo(int colorsToTrack = 2)
    {
       trackingColorRanges = new TrackColorRange[colorsToTrack]; 
       ... 
       showPointLocations = new PictureBox[colorsToTrack];  
    }
}

Use a property instead. In the property setter reallocate the arrays:

public class ColorTracker {
    private int count;
    private TrackColorRange[] trackingColorRanges;
    private PictureBox[] ShowPointLocations;

    public ColorTracker(int count) {
        Count = count;
    }
    public int Count {
       get { return count; }
       set {
           if (value <= 0) throw ArgumentOutOfRangeException();
           count = value;
           TrackColorRange = new TrackColorRange[value];
           ShowPointLocations = new PictureBox[value];
           // TODO: initialize array elements
           //...
       }
    }

Looks like bad design to me (consider adding a static method for changing the value and not changing it directly).

Add public before any class and any member (field, property or method) you want to access outside the assembly. (Default for classes/interfaces is internal, default for members is private.)

.Net dlls can also have config files, move this number to a config and read using ConfigurationManager . More on this can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM