c# - 在 C# 中调用静态方法

标签 c# static-methods

如何调用静态方法?我想从我创建的类中调用它,我想从 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();
        }
    }
}

最佳答案

静态类通常在您想要提供一些实用程序时使用,因此您不必创建这些类的对象。您可以通过简单地按类名调用并调用成员函数来从其他类调用这些方法。

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

希望对您有所帮助!

关于c# - 在 C# 中调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7792240/

相关文章:

c# - OpenXML 电子表格 (SpreadsheetML) 中的单元格样式

c# - 复杂对象的自动映射器映射

C# NamedValueCollection ToString 替换空格

c# - 使用现有控件向窗体添加选项卡控件

.net - 如何在派生类上动态调用静态方法

javascript - JavaScript 中的类/实例方法重写

c# - 为什么我可以将空条件运算符应用于硬编码字符串?

c# - 如何在 public static void 方法中创建消息框

java - 从另一个类访问的静态 ArrayList 始终为空

ios - NSString stringWithFormat 返回类型,为什么是 "id"?