设置基类变量的值?
这可能是一个非常愚蠢的问题,它让我感觉我的大脑已经消失了......但我无法理解如何从基类设置受保护或公共变量。
我有一个在基类中使用的枚举,但必须在继承类中设置。继承类的代码很少甚至没有,所以我特别想在方法之外执行此操作。
我想要的一个例子:
public class MyBase {
protected myEnum;
}
public class MyClass : MyBase {
myEnum = SomeValue;
}
如果我使用 get/set 将 myEnum 设置为属性,我可以覆盖它......但最终我会得到更多行代码。
如果我重写 Page_Load,我可以访问 this.myEnum,但同样,我想在方法之外访问它,因为它是继承类中的唯一代码。
我在这里错过了一些完全明显的东西吗?
This may be a very stupid question and it's making feel like my brain has gone...but I cannot fathom how to set a protected or public variable from a Base class.
I have an Enum that is used in the Base class, but must be set in the Inheriting class. The Inheriting class is very little to no code so I SPECIFICALLY want to do this outside of a Method.
An example of what I want:
public class MyBase {
protected myEnum;
}
public class MyClass : MyBase {
myEnum = SomeValue;
}
If I set myEnum as a property with get/set, I can override it...but then I end up with many more lines of code.
If I override Page_Load I can access this.myEnum
but again, I want to access it outside of a method as it is the only code in the Inheriting class.
Am I missing something completely obvious here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要创建一个构造函数。
您不能在方法之外执行代码。
You need to create a constructor.
You cannot execute code outside a method.
除非拥有(或位于)实例,否则不可能分配“实例变量”:-) [C# 确实允许对当前类定义中定义的字段和在中分配的值进行一些编译器魔法。声明;这不会扩展到任意赋值。]
虽然我个人会使用派生类的构造函数(或保证在适当时间运行的方法),但可以用来反转它的一种方法,是使用虚拟 getter:
请注意此示例访问构造函数中的虚拟方法(请参阅在基类构造函数中调用虚方法)需要小心完成: (派生类可能处于“无效状态”,因为它的构造函数主体尚未运行。)
再次注意对虚拟方法的调用,该方法可以避免在
Base
中做更多的工作(例如将 enumValue 包装在惰性加载 getter 本身中),但为了“最短的代码”......快乐编码。
It is not possible to assign an "instance variable" unless one has (or is in) an instance :-) [C# does allow some compiler magic for fields defined within the current class definition and values assigned in the declaration; this does not expand to arbitrary assignments.]
While I would personally use the constructor of the derived class (or a method guaranteed to run at an appropriate time), one way that can be used to invert this, is to use a virtual getter:
Please note this example access a virtual method in the constructor (see Calling virtual method in base class constructor) which needs to be done with care: (The derived class may be in an "invalid state" insofar as it's constructor body has not run yet.)
Once again, note the call to a virtual method, which can be avoided with a little more work in
Base
(e.g. wrap enumValue in a lazy-load getter itself), but for "shortest code"....Happy coding.
这对你有用吗?
BasePage.cs(BasePage,派生自Page):
Page.aspx.cs(派生自BasePage):
Page.aspx:
Would this work for you?
BasePage.cs (BasePage, derives from Page):
Page.aspx.cs (derives from BasePage):
Page.aspx: