如何使用变量进行访问 [英] How acess a class,with variables

查看:129
本文介绍了如何使用变量进行访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在一个类中访问变量,这个类在另一个类中?

感谢您的注意。

解决方案

< blockquote>与Java不同,在C#中没有隐式引用封闭类的实例。



您需要将这样的引用传递给嵌套类。一种典型的方法是通过嵌套类的构造函数。



这里有一个如何从嵌套类访问封闭类中的字段的示例。请看一下这篇文章:嵌套类的教程C# [ ^ ]



  public   partial   class  Form1:表单
{
private 嵌套m_Nested;

public Form1()
{
InitializeComponent();

m_Nested = new 嵌套( this );
m_Nested.Test();
}

私有 class 嵌套
{
private Form1 m_Parent;

受保护 Form1 Parent
{
get
{
return m_Parent;
}
}

public 嵌套(Form1 parent)
{
m_Parent = parent ;
}

public void 测试()
{
this .Parent.textBox1.Text = 测试对父Form控件的访问;
}
}
}


How can i acess a variable inside a class,and this class is inside an another class?
Thanks for the atention.

解决方案

Unlike Java, in C# there is no implicit reference to an instance of the enclosing class.

You need to pass such a reference to the nested class. A typical way to do this is through the nested class's constructor.

Here an example of how to access field in the enclosing class from the nested class. Take a look at this article as well please: A Tutorial on Nested Classes in C#[^]

public partial class Form1 : Form
{
    private Nested m_Nested;

    public Form1()
    {
    	InitializeComponent();

    	m_Nested = new Nested(this);
    	m_Nested.Test();
    }

    private class Nested
    {
    	private Form1 m_Parent;

    	protected Form1 Parent
    	{
    		get
    		{
    			return m_Parent;
    		}
    	}

    	public Nested(Form1 parent)
    	{
    		m_Parent = parent;
    	}

    	public void Test()
    	{
    		this.Parent.textBox1.Text = "Testing access to parent Form's control";
    	}
    }
}


这篇关于如何使用变量进行访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆