c#基础篇

来源:互联网 发布:ubuntu安装mysql失败 编辑:程序博客网 时间:2024/05/16 14:41

1.readonly 和const常量

  (1)const只能在字段的声明语句中初始化,而readonly可以在声明语句和构造函数中都可以,readonly 字段被赋值了就不能改变

  (2)readonly可以是实例字段也可以是静态字段

  (3)readonly分配内存,const不分配

  (4)const的值是在编译期决定的,readonly则是在运行期




获取公网ip

  

        /// <summary>
        /// 获取本机的上网IP
        /// </summary>
        /// <returns></returns>
        private string GetConnectNetAddress()
        {
            string strUrl = "http://www.ip138.com/ip2city.asp"; //获得IP的网址
            Uri uri = new Uri(strUrl);
            WebRequest webreq = WebRequest.Create(uri);
            Stream s = webreq.GetResponse().GetResponseStream();
            StreamReader sr = new StreamReader(s, Encoding.Default);
            string all = sr.ReadToEnd(); //读取网站返回的数据 格式:您的IP地址是:[x.x.x.x]
            int i = all.IndexOf("[") + 1;
            string tempip = all.Substring(i, 15);
            string ip = tempip.Replace("]", "").Replace(" ", "").Replace("<", "");
            return ip;
        } 


     /// <summary>
    /// 获取用户远程ip
    /// </summary>
    /// <returns></returns>
    private string GetUserHostIp()
    {
        string ip = string.Empty;
        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        }
        else if ((string.IsNullOrEmpty(ip) || ip.Length <= 0) && HttpContext.Current.Request.ServerVariables["Proxy-Client-IP"] != null)
        {
            ip = HttpContext.Current.Request.ServerVariables["Proxy-Client-IP"];
        }
        else if ((string.IsNullOrEmpty(ip) || ip.Length <= 0) && HttpContext.Current.Request.ServerVariables["WL-Proxy-Client-IP"] != null)
        {
            ip = HttpContext.Current.Request.ServerVariables["WL-Proxy-Client-IP"];
        }
        else if ((string.IsNullOrEmpty(ip) || ip.Length <= 0) && HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
        {
            ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }
        else if (string.IsNullOrEmpty(ip) || ip.Length <= 0)
        {
            ip = HttpContext.Current.Request.UserHostAddress;
        }
        return ip;
    } 

0 0
原创粉丝点击