[英]Accessing/Using nested classes from other classes C#
I have a class in a folder in my namespace as:我的命名空间中的文件夹中有一个类:
using System;
namespace mynamespace.myFolder1
{
public class F1
{
// class properties...
// class methods...
public class F1_Nest
{
// class properties...
// class methods...
}
}
Now I have to access class F1_Nest
as from:现在我必须从以下位置访问
F1_Nest
类:
using System;
using mynamespace.myFolder1;
namespace mynamespace.myFolder2
{
public class F2
{
// class properties...
// class methods...
// I have to access nested class F1_Nest here...
}
}
How will I use/access class F1_Nest
inside class F2
?我将如何在
F2
类中使用/访问F1_Nest
类?
A nested class is just like a normal class, except it's definition resides within the containing class.嵌套类是就像一个正常的类,除了它的定义驻留包含类内。 The result is that the containing class is almost like a namespace for the nested class.
结果是包含类几乎就像嵌套类的命名空间。 You don't have to instantiate the containing class in order to use the nested class.
您不必为了使用嵌套类而实例化包含类。 For instance:
例如:
namespace MyNamespace
{
public class MyParentClass
{
public class MyNestedClass
{
}
}
}
Now you can instantiate it somewhere else like this:现在你可以像这样在其他地方实例化它:
MyNamespace.MyParentClass.MyNestedClass x =
new MyNamespace.MyParentClass.MyNestedClass();
The purpose of this, like namespaces, is for organization.与命名空间一样,这样做的目的是为了组织。 It's up to you as the designer whether or not you use nested classes instead of a flat class structure, but it can be convenient when you have a class whose meaning, definition, or usage is inextricably tied to the another class and doesn't have any relevance or meaning outside of that class.
是否使用嵌套类而不是平面类结构取决于您作为设计者,但是当您有一个类的含义、定义或用法与另一个类密不可分并且没有该课程之外的任何相关性或意义。
For example, imagine you have a Widget
class which has an ID
property that's more than just a simple int
or Guid
...you might have a WidgetID
enumeration, for example that could reside as a nested class in Widget
.例如,假设您有一个
Widget
类,它的ID
属性不仅仅是一个简单的int
或Guid
……您可能有一个WidgetID
枚举,例如它可以作为嵌套类驻留在Widget
。
To access nested classes you need to do the following:要访问嵌套类,您需要执行以下操作:
using System;
using mynamespace.myFolder1;
namespace mynamespace.myFolder2
{
public class F2
{
// class properties...
// class methods...
void SomeMethod()
{
// no need to instantiate an object of F1 class
var f1Nest = new F1.F1_Nest();
}
}
}
The nested class F1_Nest
can be accessed in class F2
as:嵌套类
F1_Nest
可以在类F2
访问为:
using System;
using mynamespace.myFolder1;
namespace mynamespace.myFolder2
{
public class F2
{
// class properties...
// class methods...
// I have to access nested class F1_Nest here...
void F2_Method()
{
F1.F1_Nest();
}
}
}
声明F1_Nest的对象如下
F1.F1_Nest objYourObjectVariableName=new F1.F1_Nest();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.