簡體   English   中英

如何從字符串調用靜態類方法?

[英]How to call static class method from string?

當我是新手和學習者時,請原諒我的無知/錯誤。 我有一個靜態班級,上面有國家名稱, Finland ,如下所示。

namespace Countries
{
    public static class Finland
    {
        public static int ID { get; set; } = 7;
        public static string nameOfCountry { get; set; } = "Finland";
        public static string abbreviation { get; set; } = "FI";
        public static string flagLocation { get; set; } = "finishFlag.png";
        public static string GetFlag()
        {
            return "finishFlag.png";
        }
    }
}

我正在使用HttpClient從網站上執行GET請求JSON字符串。 然后,我使用DeserializeObject將JSON反序列化為一個對象。 對象的變量之一是string countryName (與string countryName完全匹配)。 通過使用此字符串(countryName),我想從相應的國家/地區類別調用GetFlag()方法。 但是,我不知道如何從字符串countryName調用此靜態方法。 我可以將nameOfCountry字符串與countryName字符串進行比較,但是我有24個國家/地區類別,例如Finland類,這意味着如果if語句為24。

我從StackOverflow的答案之一中看到了Type.GetType()方法,但是由於我沒有創建實例,所以我不明白如何在這里使用它。 請提供解決方案的示例,以使其更易於理解。 謝謝。

您不需要24個不同的類,而需要1個具有24個實例的類。

public class Country
{
    public int ID { get; }
    public string NameOfCountry { get; }
    public string Abbreviation { get; }
    public string FlagLocation { get; }

    public Country(int id, string nameOfCountry, string abbreviation, string flagLocation)
    {
        ID = id;
        NameOfCountry = nameOfCountry;
        Abbreviation = abbreviation;
        FlagLocation = flagLocation;
    }        
}

請注意,如果這些屬性在問題中是static的,則所有實例將共享該值,這是您在此處不需要的。

存儲這些類的最佳方法(假設您無法使用數據庫)將是使用Dictionary:

private static Dictionary<string, Country> _countries = new Dictionary<string, Country>
{
    ["Finland"] = new Country(7, "Finland", "FI", "finishFlag.png"),
    ["USA"] = ...
};

然后,您可以按它們的名稱訪問這些國家:

Country country = _countries["Finland"];

這樣,將國家/地區添加到字典中比創建新類和添加新的if案例要容易得多。

不要創建一堆靜態類。 而是創建一個Country類,然后創建每個國家的對象。

public class Country
{
    public int ID { get; set; }
    public string Name { get; set; }
    public tring Abbreviation { get; set; }
    public tring FlagLocation { get; set; }
}

然后你可以有一個靜態字典

public static Dictionary<string, Country> Countries = 
{
    ["Finland"] = new Country
    {
        ID = 7,
        Name = "Finland",
        Abbreviation = "FI",
        FlagLocation = "finishFlag.png"
    },
    ["Germany"] = new Country
    {
        ID = 8,
        Name = "Germany",
        Abbreviation = "DE",
        FlagLocation = "germanFlag.png"
    }
}

然后給定一個國家的名字,你可以得到像這樣的旗幟位置

Countries["Finland"].FlagLocation;

如果僅使用靜態類,則不能依賴類之間的任何公共結構(靜態類不能參與多態性)。

相反,如果您使用接口定義國家/地區,並且在代碼中的某處初始化了每種國家/地區類型的單例實例該怎么辦? 然后,當您返回一個字符串時,可以搜索具有正確國家名稱的實例,並使用您認為合適的其余信息。

作為@juharr答復的替代方法,您可以使用一個接口,然后讓每個國家/地區將其作為專用類來實現; 如果您發現自己需要這種行為,則可以使用特定國家/地區的行為。 如果您不這樣做,那么@juharr的答案是有效的。

public interface ICountry
{
    int Id { get; }

    string Name { get; }

    // .. and so on.
}

public class Finland : ICountry
{
    public string Name { get; private set; } = "Finland";

    public int Id { get; private set; } = 7;
}

public class CountryRegistry
{
    private Dictionary<string, ICountry> countryMap;

    public CountryRegistry()
    {
        this.countryMap = new Dictionary<string, ICountry>();

        InitCountries();
    }

    public ICountry FindByName( string searchName )
    {
        ICountry result;
        if( this.countryMap.TryGetValue( searchName, out result ) )
        {
            return result;
        }
        else
        {
            return null;
        }
    }

    private void InitCountries()
    {
        AddCountryToMap( new Finland() );
        // .. and so on
    }

    private void AddCountryToMap( ICountry country )
    {
        this.countryMap.Add( country.Name, country );
    }
}

將對象聲明為類在程序員的世界中並不常見。 類是定義模板(和行為集合)的地方。 您可以通過以下方式定義國家/地區類別:

public class Country    
{
    public int ID { get; set; };
    public string NameOfCountry { get; set; };
    public string Abbreviation { get; set; };
    public string FlagLocation { get; set; };
}

然后將您的國家/地區定義為靜態對象:

 static Country Finland = new Country() { ID = 7, 
                                          NameOfCountry="Finland",
                                          Abbreviation  = "FI",
                                          FlagLocation = "finishFlag.png"
                                         };

暫無
暫無

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

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