创建几个设置实例

时间:2013-12-09 18:59:51

标签: c# textbox settings

我即将创建一个我想要测量的应用程序,因此能够存储大量加速度计的设置。问题在于我现在还不知道有多少,因此我希望能够为每个设置创建加速度计设置的新实例(加速度计的名称,频率范围等)。加速度计我添加到系统中。为了能够配置设置,我添加了一个ListBox,它将显示加速度计的名称,当点击此框中的项目时,页面上的文本框应填充设置。

......至少那是理论。有谁知道如何基于文本框中的字符串创建我的AccelerometerSettings类的实例?也就是说,而不是;

    AccelerometerSettings SomeRandomAccelerometer = New AccelerometerSettings();

我想

    AccelerometerSettings TheNameTypedInTheTextBox = New AccelerometerSettings();

每个新的加速度计。或者我完全误解了SettingsClass的工作原理?

如何在ListBox中显示所有加速度计,并在点击时将设置显示在文本框中?

非常感谢提前!

2 个答案:

答案 0 :(得分:1)

您似乎有一些基本的理解问题。

AccelerometerSettings TheNameTypedInTheTextBox = New AccelerometerSettings();

是AccelerometerSettings类型的变量的c#声明,它也被初始化为新的对象实例。

要在运行时维护命名的设置集合,您应该使用集合类。

例如,您可以使用字典类

Dictionary<TKey,TValue>

将您的字典声明并初始化为

var MySettings = new Dictionary<string,AccelerometerSettings>();

使用MySettings上的Add()方法添加具有名称的新实例(由用户提供)。字典

答案 1 :(得分:1)

这是一个非常基本的,天真的实现,可以实现接近你所期待的目标。它可以大大改进,但它应该让你走上正确的轨道。

using System.Collections.Generic;

class SettingsManager
{
    Dictionary<string, AcceleromterSettings> settings;

    // contructor for SettingsManager class; a fundamental C# concept
    public SettingsManager()
    {
        LoadSettings();
    }

    // creates new instances of AccelerometerSettings and stores them
    // in a Dictionary<key, value> object for later retrieval. The
    // Dictionary object uses a unique-key to access a value
    // which can be any object.
    void LoadSettings()
    {
        settings = new Dictionary<string, AcceleromterSettings>();

        AcceleromterSettings horizontal = new AcceleromterSettings();
        horizontal.AttributeOne = 101;
        horizontal.AttributeTwo = 532;
        horizontal.AttributeThree = 783;
        settings.Add("Horizontal", horizontal);

        AcceleromterSettings vertical = new AcceleromterSettings();
        vertical.AttributeOne = 50;
        vertical.AttributeTwo = 74;
        vertical.AttributeThree = 99;
        settings.Add("Vertical", vertical);
    }

    // Retrieves settings from the Dictionary while hiding
    // specific implementation details.
    public AcceleromterSettings GetSettings(string name)
    {
        AcceleromterSettings setting = null;

        // this method of Dictionary returns a Boolean value indicating
        // whether or not the value retrieval worked. If the Key is found
        // in the dictionary, the 'out' parameter is modified reflect
        // the value, and the method returns true. If the key is not found
        // the 'out' parameter is not modified, and the method returns false.
        if (!settings.TryGetValue(name, out setting))
            throw new ArgumentException(string.Format("Settings not found for settings name {0}", name));

        return setting;
    }
}