在 C# 中调用静态方法
如何调用静态方法?我想从我创建的类中调用它,我想从 IP 获取位置。我已经声明了它,但我需要做的是调用该方法...作为 static
...
老实说,我在这里很困惑,我需要实例化 地址
、城市
等?
到目前为止我已经这样做了;
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();
}
}
}
}
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... as static
...
To be honest with you, I'm quite confused here, do I need to instantiate address
, city
, etc.?
I have done this so far;
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();
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
静态类通常在您想要提供一些实用程序时使用,因此您不必创建这些类的对象。您可以通过简单地按类名调用并调用成员函数来从其他类调用这些方法。
例如,在这里您可以调用 LocationTools.GetLocationFromIP();
希望有帮助!
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!
就这样吧
There you go
您应该在 MSDN 上阅读有关静态类和成员的信息
You should read up about Static Classes and Members on MSDN
您需要做两件事:
首先,导入静态类所在的库:
import blabla;
然后,调用静态方法执行如下操作:
LocationTools.GetLocationFromIP(address, city...);
它应该有效。
You need to do two things:
First, import the library where the static class is:
import blabla;
Then, call your static method doing something liked this:
LocationTools.GetLocationFromIP(address, city...);
It should work.
它就像这样简单:
只需调用类,然后直接调用方法。静态意味着您不需要类的实例来调用该方法。
It's as easy as:
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.