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 in开发者_如何学运维t 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.
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
//...
}
}
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];
}
}
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.
精彩评论