簡體   English   中英

如何從 c# 中的另一個類調用字典值?

[英]How do I call a dictionary value from another class in c#?

我在 C# 中創建了一個表單。 我想在單擊按鈕時顯示儀表的值。 如何從另一個類中引用字典術語?

using System;

public class Dictionary
{
    public void References()
    {
        Dictionary<string, double> Length = new Dictionary<string, double>(Lengths);

        Length.Add("Feet", 1);
        Length.Add("Meters", 0.3048);
    }
}

這個函數在另一個類中

    private void Done_Button_Click(object sender, EventArgs e)
    {
        double Meter_Feet = Dictionary.Length("Meters");

        MessageBox.Show("Meter_Feet");
    }

你可以在你的第一個類中創建一個公共屬性:

public class Dictionary
{
    public Dictionary<string, double> Length {get;}
    public void References()
    {
        Length = new Dictionary<string, double>(Lengths);

        Length.Add("Feet", 1);
        Length.Add("Meters", 0.3048);
    }
}

然后你可以這樣引用它:

    private void Done_Button_Click(object sender, EventArgs e)
    {
        var dictionary = new Dictionary();

        dictionary.References();
        double Meter_Feet = dictionary.Length["Meters"];

        MessageBox.Show(Meter_Feet);
    }

創建與常用System類(如Dictionary )同名的類不是一個好習慣。 它會造成混亂,並且通常還會迫使用戶使用完全限定的名稱來引用他們想要的名稱。

如果你想讓一個類成員被其他類訪問,那么你應該將它(或它的屬性訪問器)聲明為你的類的public成員。 此外,不需要調用單獨的方法來填充字典,您可以將該代碼放在構造函數中,以便自動調用它,例如:

public class ConverterDictionary
{
    public Dictionary<string, double> Units { get; }

    public ConverterDictionary()
    {
        Units = new Dictionary<string, double>
        {
            {"Feet", 1},
            {"Meters", .3048}
        };
    }
}

然后客戶端只需要初始化你的類來獲取字典:

double Meter_Feet = new ConverterDictionary().Units["Meters"];

但是,您似乎正在嘗試創建某種轉換類,在這種情況下,您可能需要考慮不同的設計。 例如,您可以創建一個靜態類,該類具有您想要執行的轉換類型的方法。 靜態類的好處是客戶端不必實例化它——他們可以只調用方法。 這適用於轉換類,因為轉換率是靜態的(它們永遠不會改變)。

例如:

public static class ConvertUnits
{
    private const double MetersPerFoot = .3048;
    private const double FeetPerMeter = 3.281;

    public static double FromFeetToMeters(double feet)
    {
        return feet * MetersPerFoot;
    }

    public static double FromMetersToFeet(double meters)
    {
        return meters * FeetPerMeter;
    }
}

然后你可以像這樣使用這個類:

private static void Main()
{
    double feet;

    // Get input from user in a loop to ensure they enter a valid double
    do
    {
        Console.Write("Enter number of feet to convert to meters: ");
    } while (!double.TryParse(Console.ReadLine(), out feet));

    // Now we can use our converter class without any instantiation needed
    double result = ConvertUnits.FromFeetToMeters(feet);

    Console.WriteLine($"\nThere are {result} meters in {feet} feet.");

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

輸出

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM