简体   繁体   English

dll 和 static 变量问题中的 C# 库

[英]C# library in dll and static variable problem

I want to make a library in.dll so it can be reused.我想在.dll 中创建一个库,以便可以重复使用。 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.使用该库的用户应该能够说出要跟踪的 colors 的数量是多少,如果我想以我想要的方式使用它,我已经把这些数据放在变量“num”中,它必须是 static。

    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.现在如果用户直接使用代码没有问题,但是如果我把它放在a.dll 用户不能改变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 的可选构造函数参数,然后在构造函数中初始化您的实例变量:

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:在属性设置器中重新分配 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).在我看来设计很糟糕(考虑添加一个 static 方法来更改值而不是直接更改它)。

Add public before any class and any member (field, property or method) you want to access outside the assembly.在任何 class 和要在程序集外部访问的任何成员(字段、属性或方法)之前添加 public。 (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 . .Net dll 也可以有配置文件,将此编号移动到配置并使用ConfigurationManager读取。 More on this can be found here .更多信息可以在这里找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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