如果我有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();
}
Run Code Online (Sandbox Code Playgroud)
这是什么解决方案?
基本上,为了从类到类访问信息,您必须在实例之间以某种方式"传递"该信息.
以下是使用基本设置的快速注释示例.我已经包含了一些关于在对象之间发送信息的不同方法的示例:
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
}
}
Run Code Online (Sandbox Code Playgroud)
当然,那些都使用.NET的自动属性.对于简单的实现,它们工作正常.但是,如果您需要(或者只是想)拆分成员,请使用完整属性语法.
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你注意到,这会_cc在成员声明中初始化私有.这确保了cc在使用之前不需要显式初始化该属性.同样,这是一个比刚性标准更好的例子.了解.NET使用属性和私有成员的所有方式非常重要,因此您可以根据自己的具体情况选择和使用最佳方法.
此外,作为一个侧面说明,你会发现,我既包含private或public在每个私有成员,属性和构造函数的前面.虽然技术上不必要,但通常的做法是明确指定每个类成员的可访问性级别(这会促进封装).关于封装的维基百科文章有一个相当不错的介绍性解释和例子.
对于未来,我还建议您查看一组.NET命名约定,例如属性名称,支持字段,方法名称等:
虽然您可能很好地阅读自己的代码,但遵循这些不同的命名约定可确保其他人也能够更好地阅读和理解它.
| 归档时间: |
|
| 查看次数: |
42570 次 |
| 最近记录: |