ASP.NET初学者问题:如何在classB中使用classA的变量?

时间:2010-09-11 11:35:02

标签: c# asp.net

我想在这个类Geolocation error with IP address 127.0.0.1

中使用变量“iso3166TwoLetterCode”的值

在我的新测试课程中,我该如何使用它?我甚至可以使用它吗?如果有,怎么样?我需要这个变量在if语句中使用它来检查国家代码,并根据国家代码,更改母版页。

2 个答案:

答案 0 :(得分:3)

我建议你将这个功能提取到一些可以从PageA和PageB中重用的实用程序类中:

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 :(得分:1)

首先不能使用该变量的原因是它只在本地范围内定义 - 即编译器在赋值后到达下一个}时 - 变量和它的值都消失了。如果你要在同一个类中使用该变量,你可以使它成为一个类'字段,因为你需要在另一个类中使用它,你可以使它静态(在这种情况下没有意义)或使用达林的解决方案。跟着达林的解决方案( - :