如何在C#中的多个类实例之间共享一个值?

Mik*_*man 0 c# variables class object

我正在编写一个类库,用于我们公司的一些工程软件.该库用于定义结构钢形状的属性.在我的每个类对象中,我需要转到指定的文件夹并查找一些xml数据.

我怎样才能创建一个公共变量,我可以在库类之外设置并在实例之间共享如下所示:(如果可以使用以下代码)

    class Program
{
    static void Main(string[] args)
    {
        string someCommonVarialble = @"c:\some\path\where\the\xmlData\are\stored";

        // create some steel shapes
        SteelBeamShape myBeam1 = new SteelBeamShape("W6x9");
        SteelBeamShape myBeam2 = new SteelBeamShape("W10x22");
        SteelPipeShape myPipe1 = new SteelPipeShape("10odx.375wall");
        SteelPipeShape myPipe2 = new SteelPipeShape("24odx.750wall");

        // do some work with objects here
    }
}

public class SteelBeamShape
{
    // constructor
    public SteelBeamShape(string SteelBeamNominalValue)
    {
        // look up some properties base on nominal value in XML tables
        this.xmlDataPath = someCommonVariable;

        // do stuff .... 
    }
}

public class SteelPipeShape
{
    // constructor
    public SteelPipeShape(string SteelPipeNominalValue)
    {
        // look up some properties base on nominal value in XML tables
        this.xmlDataPath = someCommonVariable;

        // do stuff .... 
    }
}
Run Code Online (Sandbox Code Playgroud)

}

pln*_*pln 5

我会考虑首先加载xml数据,然后通过构造函数或类中的方法发送数据进行实际工作.

否则你可能在你的类中有重复的代码基本上做同样的事情(加载数据,查找xml数据等).