在C#中调用静态方法

16
如何调用静态方法?我想从我创建的类中调用它,我想通过IP获取位置。我已经声明了它,但我需要做的是调用这个方法...作为static...
说实话,我在这里很困惑,我需要实例化addresscity等吗?
到目前为止,我已经做到了这一点;

LocationTools.cs

public static class LocationTools
    {
        public static void GetLocationFromIP(string address, out string city, out string region, out string country, out double? latitude, out double? longitude)
        {

Home.cs

   public string IPAPIKey
    {
       get
        {
            return WebConfigurationManager.AppSettings["IPAPIKey"];
        }
    }

    ////To get the ip address of the machine and not the proxy use the following code
    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();
        }
    }
}

}


2
你尝试了什么?只需使用LocationTools.GetLocationFromIP(...)函数即可。 - Davide Piras
5个回答

10

静态类通常用于提供一些工具,因此您不必创建这些类的对象。您可以通过类名直接调用这些方法,并调用成员函数从其他类中调用它们。

例如,在此处您可以调用 LocationTools.GetLocationFromIP();

希望这可以帮助!


5

请看这里。

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

2
LocationTools.GetLocationFromIP( ... ) ;

你应该阅读关于静态类和成员的相关内容,可以在MSDN上查找。静态类和静态成员用于创建可以在不创建类实例的情况下访问的数据和函数。静态类成员可用于分离与任何对象标识无关的数据和行为:无论发生什么情况,数据和函数都不会改变。当类中没有依赖于对象标识的数据或行为时,可以使用静态类。请注意保留HTML标签。

1

这很简单:

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

只需调用该类,即可直接调用方法。静态意味着您不需要类的实例来调用该方法。

它们是输出变量,而不是输入变量。 - Russ Clarke
没看到它们...这样更好吗? - Hidde

1
你需要做两件事情:
  1. 首先,导入静态类所在的库: import blabla;

  2. 然后,调用你的静态方法,像这样做一些事情: LocationTools.GetLocationFromIP(address, city...);

它应该可以工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接