C# 我们可以为嵌套类设置构造函数吗?
绝对-与您通常使用的方式相同:C# 我们可以为嵌套类设置构造函数吗?,c#,C#,绝对-与您通常使用的方式相同: In the below example i want to create folder in nested class constructor: namespace Nm { class Outer { private const string s1 = "@.\bin"; void O1() { Neste
In the below example i want to create folder in nested class constructor:
namespace Nm
{
class Outer
{
private const string s1 = "@.\bin";
void O1()
{
Nested nestedFile = new Nested();
nestedFile.FileName = "Queue1";
}
}
internal class Nested
{
public string FileName
{
set
{
Directory.CreateDirectory(s1); // !
fileName = s1+ value + ".dat";
Console.writeLine(fileName);
}
}
}
}
绝对-与您通常使用的方式相同:
In the below example i want to create folder in nested class constructor:
namespace Nm
{
class Outer
{
private const string s1 = "@.\bin";
void O1()
{
Nested nestedFile = new Nested();
nestedFile.FileName = "Queue1";
}
}
internal class Nested
{
public string FileName
{
set
{
Directory.CreateDirectory(s1); // !
fileName = s1+ value + ".dat";
Console.writeLine(fileName);
}
}
}
}
只要您的类是
内部的
(而不是外部的私有的),您就可以执行下一步操作:
class Outer
{
private void Foo()
{
Nested nested = new Nested("bar");
}
class Nested
{
internal Nested(string x)
{
...
}
}
}
但是程序集中的任何类都可以访问此字段,只要您的类是
内部的
(而不是外部的-私有的
),您可以执行以下操作:
class Outer
{
private void Foo()
{
Nested nested = new Nested("bar");
}
class Nested
{
internal Nested(string x)
{
...
}
}
}
但程序集中的任何类都可以访问此字段OK。我已经对第一个实例化的嵌套类进行了一些处理/验证。然后在某个时刻,外部类更改了s1的值,然后?@starz26:strings在.NET中是不可变的,所以每次您更改它时,您都会创建一个新实例。因此,无论如何,外部字符串更改不会影响传递给嵌套字符串的字符串class@starz26,如果是const,则不能更改该值,但如果将其设置为私有字段成员并将外部类的实例传递给嵌套构造函数,则嵌套构造函数可以访问该私有字段。这是嵌套类的主要好处之一,因为它允许您拥有类封装的好处(组织职责),但您仍然需要共享紧耦合状态。好的。我已经对第一个实例化的嵌套类进行了一些处理/验证。然后在某个时刻,外部类更改了s1的值,然后?@starz26:strings在.NET中是不可变的,所以每次您更改它时,您都会创建一个新实例。因此,无论如何,外部字符串更改不会影响传递给嵌套字符串的字符串class@starz26,如果是const,则不能更改该值,但如果将其设置为私有字段成员并将外部类的实例传递给嵌套构造函数,则嵌套构造函数可以访问该私有字段。这是嵌套类的主要好处之一,因为它允许您获得类封装的好处(组织职责),但您仍然需要共享紧密耦合的状态。