Calling a Static method in C#

前端 未结 5 1421
[愿得一人]
[愿得一人] 2021-02-19 11:46

How do I call a static method? I want to call this from a class I have created, I want to get the location from IP. I\'ve declared it but what I need to do is call the method...

相关标签:
5条回答
  • 2021-02-19 12:09

    Static classes are generally used when you want to provide some utilities, so you do not have to create objects of those classes. You can call those methods from other classes by simply calling by class name and invoking the member function.

    For example here you can call as LocationTools.GetLocationFromIP();

    Hope it helps!

    0 讨论(0)
  • 2021-02-19 12:09
    LocationTools.GetLocationFromIP( ... ) ;
    

    You should read up about Static Classes and Members on MSDN

    Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

    0 讨论(0)
  • 2021-02-19 12:11

    There you go

    static void GetLocationFromIP()
    {
        string strIPAddress = Request.UserHostAddress.ToString();
        strIPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    
        if (strIPAddress == null || strIPAddress == "")
        {
            strIPAddress = Request.ServerVariables["REMOTE_ADDR"].ToString();
        }
    
        string city = string.Empty;
        string region = string.Empty;
        string country = string.Empty;
        double latitude = -1.00;
        double longitude = -1.00;
    
        LocationTools.GetLocationFromIP(strIPAddress, out city, out region, out country, out latitude, out longitude)
    }
    
    0 讨论(0)
  • 2021-02-19 12:13

    It's as easy as:

    LocationTools.GetLocationFromIP(strIP, strCity, strRegion, strCountry, fLat, fLong)
    

    Just call the Class, and straight from that the method. Static means that you do not need an instance of the class to call the method.

    0 讨论(0)
  • 2021-02-19 12:15

    You need to do two things:

    1. First, import the library where the static class is: import blabla;

    2. Then, call your static method doing something liked this: LocationTools.GetLocationFromIP(address, city...);

    It should work.

    0 讨论(0)
提交回复
热议问题