从静态函数引用非静态字段,反之亦然? [英] Referencing non-static fields from static functions and vice versa impossible?
问题描述
我想以编程方式确定我想要动态创建的一些控件的空间。所以,我想获取容器的高度,并将其除以行数(一个常量)。
I want to programmatically determine the space I've got for some controls I want to create dynamically. So, I want to get the container's height and divide it by the number of rows (a constant).
我有这个功能(这段代码是名为dynamicPanel的面板的形式):
I've got this function (this code is part of the form on which the panel named dynamicPanel lives):
private static int getControlHeightToUse() {
return (dynamicPanel.Height / NUMBER_OF_ROWS);
}
...这给我编译时错误,*一个对象非静态字段,方法或属性需要参考RememberNextGen_CRLogins.CRLoginsMainForm.dynamicPanel'*
...which gives me the compile-time error, "*An object reference is required for the non-static field, method, or property RememberNextGen_CRLogins.CRLoginsMainForm.dynamicPanel'*"
我不明白是什么告诉我/什么它想要。
I don't understand what it's trying to tell me/what it wants.
如果我删除静态:
private int getControlHeightToUse() {
return (dynamicPanel.Height / NUMBER_OF_ROWS);
}
...然后我得到编译时错误,* A字段初始化程序无法引用下面指示的非静态字段,方法或属性TitanNextGen_CRLogins.CRLoginsMainForm.getControlHeightToUse()'*
...I then get the compile-time error, "*A field initializer cannot reference the non-static field, method, or property 'TitanNextGen_CRLogins.CRLoginsMainForm.getControlHeightToUse()'*"
...
...on the indicated line below:
public partial class CRLoginsMainForm : Form {
int controlHeight = getControlHeightToUse(); // <-- err
推荐答案
A static
方法只能直接访问该类的 static
memebers,如果要使用该类的实例成员,则必须通过在类的一个实例中(或者有一个可用作为 static
,如单例)。
A static
method has only direct access to static
memebers of the class, if you want to use instance members of the class, you must pass in an instance of the class to the method (or have one available as a static
as in the case of a singleton).
因此,您可以修改方法来接收阻止它的静态实例成员:
Thus, you can modify your method to take in the instance member that is preventing it from being able to be static:
private static int getControlHeightToUse(Panel thePanel)
{
return (thePanel.Height / NUMBER_OF_ROWS);
}
然后只需传入 dynamicPanel
在调用...
Then just pass in dynamicPanel
on the call...
然而,实例方法可以访问 static
成员。记住,即使没有类的实例,成员在所有实例之间共享,并且存在。因此,他们不能调用实例成员,因为他们不知道你正在谈论哪个实例。
Instance methods, however, can access static
members. Remember that static
members are shared among all instances and exist even if no instance of the class exist. Thus they can't call instance members since they don't know which instance you are talking about.
这篇关于从静态函数引用非静态字段,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!