gpt4 book ai didi

c# - 嵌套类型是隐式静态的吗?

转载 作者:太空狗 更新时间:2023-10-30 00:02:42 25 4
gpt4 key购买 nike

在 C# 5.0 语言规范中它说:

Note that constants and nested types are classified as static members.

所以如果我写:

class A
{
int a;

class B
{
public void foo()
{
int j = a; // ERROR
}
}
}

a 到 j 的赋值给我一个 CS0120 错误

"An object reference is required for the nonstatic field, method, or property 'member'"

所以我可以理解 foo 也是隐式静态的。

然而,当我查看反编译代码和 IL 代码时,没有指示 static 关键字!

internal class A
{
private class B
{
public void foo()
{
}
}

private int a;
}


// Nested Types
.class nested private auto ansi beforefieldinit B
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig
instance void foo () cil managed
{

}
...
}

嵌套类型真的是所有方法都隐式静态的静态类型吗?

最佳答案

“嵌套类型被归类为静态成员”

Is a nested type really a static type with all methods implicitly static?

否 - Type 的定义是静态成员,但类型本身不是静态的。

当它说

Note that constants and nested types are classified as static members.

这意味着您可以在没有父类实例的情况下创建嵌套类的实例。

换句话说,用代码

public class Parent
{
public class Child
{
}
}

要调用 new Parent.Child() ,您不需要先调用 new Parent() 或类似的东西。


你的代码有问题

您的实际问题是嵌套类型的实例与父类型的实例是分开的 - 您的代码,

class A
{
int a;

class B
{
public void foo()
{
int j = a; // ERROR
}
}
}

无法编译,因为在 A.B.foo() 中,字段 aA 的一个 instance (i.e. not static) member,并且 B 没有要引用的 A实例


如何使用 一种使用嵌套类型的方法

您可以将类型嵌套视为将父级中私有(private)成员的可访问性扩展到子级的一种方式,例如

public class Parent
{
private int field;

public class Child
{
public void WriteFieldFromParent(Parent parent)
{
Console.WriteLine(parent.field);
}
}
}

编译!你可以从field类中获取Parentprivate字段Parent.Child的值,因为它是嵌套的。请注意,我需要将 Parent 的实例传递给 Parent.Child.WriteFieldFromParent

事实上,MSDN page on nested types(我不知道为什么我在第一次写这个答案时没有提到它)给出了一个类似于我的例子,并说:

A nested type has access to all of the members that are accessible to its containing type. It can access private and protected members of the containing type, including any inherited protected members.

关于c# - 嵌套类型是隐式静态的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35201749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com