简体   繁体   English

如何从字符串调用静态类方法?

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

Excuse my ignorance/mistake as I'm a newbie and learning. 当我是新手和学习者时,请原谅我的无知/错误。 I have a static class with the name of the country, Finland , as seen below. 我有一个静态班级,上面有国家名称, 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";
        }
    }
}

I'm using HttpClient to do GET request a JSON string from a website. 我正在使用HttpClient从网站上执行GET请求JSON字符串。 Then I use DeserializeObject to deserialize JSON to an object. 然后,我使用DeserializeObject将JSON反序列化为一个对象。 One of the variables of the object is string countryName (which exactly matches the string, nameOfCountry). 对象的变量之一是string countryName (与string countryName完全匹配)。 By using this string (countryName), I want to call the GetFlag() method from the respective country class. 通过使用此字符串(countryName),我想从相应的国家/地区类别调用GetFlag()方法。 However, I don't know how to call this static method from the string countryName . 但是,我不知道如何从字符串countryName调用此静态方法。 I can compare nameOfCountry string in with the countryName string, however I have 24 country classes like the class Finland which means 24 if else if statements. 我可以将nameOfCountry字符串与countryName字符串进行比较,但是我有24个国家/地区类别,例如Finland类,这意味着如果if语句为24。

I saw the Type.GetType() method from one of the answers in StackOverflow but I didn't understand how this can be used here as I'm not creating a instance. 我从StackOverflow的答案之一中看到了Type.GetType()方法,但是由于我没有创建实例,所以我不明白如何在这里使用它。 Please provide an example to solution so that it's easier to understand. 请提供解决方案的示例,以使其更易于理解。 Thank you. 谢谢。

You don't need 24 different classes, you need 1 class with 24 instances. 您不需要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;
    }        
}

Notice that if those properties were static as in the question, all instances would share the value, which is something you don't want here. 请注意,如果这些属性在问题中是static的,则所有实例将共享该值,这是您在此处不需要的。

The best way to store these classes (assuming you cannot use a database) would be to use a Dictionary: 存储这些类的最佳方法(假设您无法使用数据库)将是使用Dictionary:

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

You can then access these countries by their name: 然后,您可以按它们的名称访问这些国家:

Country country = _countries["Finland"];

Adding countries to the dictionary is then much easier than creating a new class and adding a new if case. 这样,将国家/地区添加到字典中比创建新类和添加新的if案例要容易得多。

Don't create a bunch of static classes. 不要创建一堆静态类。 Instead create one Country class then create objects of each country. 而是创建一个Country类,然后创建每个国家的对象。

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

Then you can have a static dictionary 然后你可以有一个静态字典

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"
    }
}

Then given the name of a country you can get the flag location like this 然后给定一个国家的名字,你可以得到像这样的旗帜位置

Countries["Finland"].FlagLocation;

If you use only static classes, you cannot rely on any common structure between classes (static classes cannot participate in polymorphism). 如果仅使用静态类,则不能依赖类之间的任何公共结构(静态类不能参与多态性)。

Instead, what if you defined your countries using an interface, and somewhere in your code you initialized a singleton instance of each of your country types? 相反,如果您使用接口定义国家/地区,并且在代码中的某处初始化了每种国家/地区类型的单例实例该怎么办? Then, when you get a string back, you could search for the instance that has the right country name, and use the rest of the information as you see fit. 然后,当您返回一个字符串时,可以搜索具有正确国家名称的实例,并使用您认为合适的其余信息。

As an alternative to @juharr's reply, you could use an interface, and then have each country implement that interface as a dedicated class; 作为@juharr答复的替代方法,您可以使用一个接口,然后让每个国家/地区将其作为专用类来实现; this lets you have country-specific behavior, if you were to find that you need it. 如果您发现自己需要这种行为,则可以使用特定国家/地区的行为。 If you don't, then @juharr's answer is effective. 如果您不这样做,那么@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 );
    }
}

declaring an object as a class is not common in programmer's world. 将对象声明为类在程序员的世界中并不常见。 class is somewhere to define a template (and a collection of behaviors). 类是定义模板(和行为集合)的地方。 you can define country class in this way: 您可以通过以下方式定义国家/地区类别:

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

and then define your countries as static objects: 然后将您的国家/地区定义为静态对象:

 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