2010-09-11 36 views

回答

3

我建議你提取這個功能集成到一些實用工具類,你可以從兩個網頁A和網頁B重用:

public class Country 
{ 
    public string Name { get; set; } 
    public string Iso3166TwoLetterCode { get; set; } 

    public static Country GetCountry(string userHost) 
    { 
     IPAddress ipAddress; 
     if (IPAddress.TryParse(userHost, out ipAddress)) 
     { 
      return new Country 
      { 
       Name = ipAddress.Country(), 
       Iso3166TwoLetterCode = ipAddress.Iso3166TwoLetterCode() 
      }; 
     } 
     return null; 
    } 
} 

然後在你的頁面:

protected void Page_Load(object sender, EventArgs e) 
{ 
    //Code to fetch IP address of user begins 
    string userHost = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 
    if (String.IsNullOrEmpty(userHost) || 
     String.Compare(userHost, "unknown", true) == 0) 
    { 
     userHost = Request.Params["REMOTE_ADDR"]; 
    } 

    Label1.Text = userHost; 
    var country = Country.GetCountry(userHost); 
    if (country != null) 
    { 
     Label2.Text = country.Name; 
     Label3.Text = country.Iso3166TwoLetterCode; 
    } 
} 

現在可以重用Country從另一個頁面的類。根據您的要求,您甚至可以通過向函數和返回類型傳遞附加參數進一步對其進行自定義。

1

不能像原來那樣使用該變量的原因是,它只在本地作用域中定義 - 即編譯器在賦值後到達下一個}時 - 變量和值都消失了。如果你想在同一個類中使用該變量,你可以將它作爲一個類的字段,因爲你需要在另一個類中使用它,你可以使它成爲靜態的(在這種情況下沒有意義),或者使用達林的解決方案。去達林的解決方案( - :