繁体   English   中英

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

[英]ASP.NET beginner question: How do I use classA's variable in classB?

我想使用此类的变量“ iso3166TwoLetterCode”的值,IP地址为127.0.0.1的地理位置错误

在我的新测试课程中,如何使用它? 我什至可以使用吗? 如果是,怎么办? 我需要在if语句中使用此变量来检查国家/地区代码,并根据国家/地区代码更改母版页。

我建议您将此功能提取到一些实用程序类中,以便可以从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类。 根据您的要求,您甚至可以通过将其他参数传递给函数和返回类型来进一步自定义它。

首先不能使用该变量的原因是,它仅在局部作用域中定义-也就是说,当编译器在赋值后到达下一个}时,该变量及其值均已消失。 如果要在同一类中使用该变量,则可以将其设置为类的字段,因为您需要在另一个类中使用它,因此可以将其设置为静态(在这种情况下没有意义)或使用达林的解决方案。 使用达林的解决方案(-:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM