从基类访问子类变量

时间:2021-11-12 23:05:51
class a : System.UI.Page {
int ab= c;
}
class b : a
{
public int c= 0;
}

I cant access it. I can access any control on the page by Control.NamingContainer Property in asp.net but i have to access public variable from the class(i.e. class a) that is in form(i.e. class b) so that i doesn't have write a particular method in 50 of my form.

我无法访问它。我可以通过asp.net中的Control.NamingContainer属性访问页面上的任何控件,但是我必须从类(即类a)访问表格中的公共变量(即类b),这样我就没有写一个我的形式中的50个特殊方法。

2 个解决方案

#1


2  

You could put the variable on the base class so that the inherited classes will have access to it. For example:

您可以将变量放在基类上,以便继承的类可以访问它。例如:

class a : System.UI.Page
{
    protected int c = 0;
}

class b : a
{
    protected void DoSomething()
    {
        c = 1; //Access c from derived class.
    }
}

Also, if this property is not instance specific, you can always use a static property in the Global.asax file that can be accessed from anywhere within your ASP.NET application. If it is session specific, you can simply have the property access the session and store/retrieve the value from there so that each user session has their own value.

此外,如果此属性不是特定于实例的,则可以始终在Global.asax文件中使用静态属性,该属性可以从ASP.NET应用程序中的任何位置进行访问。如果它是特定于会话的,您只需让属性访问会话并从那里存储/检索值,以便每个用户会话都有自己的值。

Hope this helps!

希望这可以帮助!

#2


0  

I think you are using inheritance in the wrong way. Try this, it should work:

我认为你以错误的方式使用继承。试试这个,它应该工作:

public class a : b {
    int ab = c;
}

public class b : System.UI.Page
{
    public int c = 0;
}

#1


2  

You could put the variable on the base class so that the inherited classes will have access to it. For example:

您可以将变量放在基类上,以便继承的类可以访问它。例如:

class a : System.UI.Page
{
    protected int c = 0;
}

class b : a
{
    protected void DoSomething()
    {
        c = 1; //Access c from derived class.
    }
}

Also, if this property is not instance specific, you can always use a static property in the Global.asax file that can be accessed from anywhere within your ASP.NET application. If it is session specific, you can simply have the property access the session and store/retrieve the value from there so that each user session has their own value.

此外,如果此属性不是特定于实例的,则可以始终在Global.asax文件中使用静态属性,该属性可以从ASP.NET应用程序中的任何位置进行访问。如果它是特定于会话的,您只需让属性访问会话并从那里存储/检索值,以便每个用户会话都有自己的值。

Hope this helps!

希望这可以帮助!

#2


0  

I think you are using inheritance in the wrong way. Try this, it should work:

我认为你以错误的方式使用继承。试试这个,它应该工作:

public class a : b {
    int ab = c;
}

public class b : System.UI.Page
{
    public int c = 0;
}