如何从另一个类访问非静态属性 [英] How to access a non-static property from another class
问题描述
我在非静态 MainForm
类中有一个非静态属性:
I have a non-static property inside a non-static MainForm
class:
public string SelectedProfile
{
get { return (string)cbxProfiles.SelectedItem; }
set { cbxProfiles.SelectedItem = value; }
}
我想从另一个非静态类获取此属性的值.使用 MainForm.SelectedProfile
会出现错误,提示非静态字段、方法或属性需要对象引用".
I would like to get the value of this property, from another non-static class. Using MainForm.SelectedProfile
gives an error saying "An object reference is required for the non-static field, method or property".
通常我会通过将 SelectedProfile
设为静态来解决这个问题,但我不能,因为无法将 cbxProfiles(一个 ComboBox 控件)设为静态.
Usually I would solve this problem by making SelectedProfile
static, but I can't, since cbxProfiles (a ComboBox control) can't be made static.
那么如何在不使其静态的情况下访问属性的值?
So how do I access the property's value without making it static?
推荐答案
您访问非静态成员的方式与总是相同:通过使用对对象实例的引用.
You access non-static members the same way you always do: by using a reference to an instance of the object.
因此,无论您希望能够使用该属性的代码是什么,您都需要向它传递一个对 MainForm
对象的引用.
So whatever code you want to be able to use that property, you need to pass it a reference to a MainForm
object.
这篇关于如何从另一个类访问非静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!