如果我有3个班级,可以说:Mainclass,ChildClass,OtherChild。
MainClass()
{
ChildClass cc = new ChildClass();
OtherChild oc = new OtherChild();
//Set the name property of childclass
string childName = "some name";
}
ChildClass()
{
public string name {get; set;}
}
OtherChild()
{
//Here i want to get the name property from ChildClass()
//Doing this will make a new instance of ChildClass, which will not have the name property set.
ChildClass cc = new ChildClass();
}
解决方案是什么?
基本上,为了从一个类到另一个类访问信息,必须在实例之间以某种方式“传递”该信息。
这是使用基本设置的带注释的快速示例。我提供了一些示例,说明如何在对象之间发送信息的不同方法:
public MainClass()
{
// just using auto-properties here. Will need initialized before use.
public ChildClass cc { get; set; }
public OtherChild oc { get; set; }
// Constructor. Gets called when initializing as "new MainClass()"
public MainClass()
{
// initialize our properties
// option 1 - initialize, then set
cc = new ChildClass();
cc.childName = "some name"; //Set the name property of childclass
//option 2 - initialize and set via constructor
cc = new ChildClass("some name");
// option 3 - initialize and set with initializer (more here: http://msdn.microsoft.com/en-us/library/vstudio/bb397680.aspx)
cc = new ChildClass() { name = "some name" };
oc = new OtherChild(cc);
}
}
public ChildClass()
{
public string name { get; set; }
// Default constructor. this.name will = null after this is run
public ChildClass()
{
}
// Other constructor. this.name = passed in "name" after this is run
public ChildClass(string name)
{
//"this.name" specifies that you are referring to the name that belongs to this class
this.name = name;
}
}
public OtherChild()
{
public ChildClass cc { get; set; }
public OtherChild()
{
cc = new ChildClass(); // initialize object in the default constructor
}
public OtherChild(ChildClass childClass)
{
cc = childClass; // set to the reference of the passed in childClass
}
}
当然,这些都使用.NET的auto-properties。对于简单的实现,它们可以正常工作。但是,如果您需要(或只是想)拆分成员,这是使用完整属性语法的示例。
public MainClass()
{
// private backing field is only accessible within this class
private ChildClass _cc = new ChildClass();
// public property is accessible from other classes
public ChildClass cc
{
get
{
return _cc;
}
set
{
_cc = value;
}
}
}
如果您注意到的话,这将_cc
在成员声明的开始处初始化私有。这样可以确保cc
在使用之前无需显式初始化该属性。同样,这比刚性标准更多的是一个例子。了解.NET使用属性和私有成员的所有方式很重要,因此您可以针对特定情况选择和使用最佳方式。
另外,作为一个附带说明,您会注意到我在每个私有成员,属性和构造函数中都包含一个private
或public
前面。尽管从技术上来讲不是必需的,但是通常最好将每个类成员的可访问性级别明确指定(这有助于封装)。维基百科有关封装的文章具有相当不错的介绍性解释和示例。
对于将来,我还建议您查看一组用于属性之类的.NET命名约定,例如属性名称,后备字段,方法名称等:
虽然您可以很好地阅读自己的代码,但遵循这些不同的命名约定可以确保其他人也能够阅读和理解它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句