gpt4 book ai didi

c# - 为什么对象实例中的枚举具有静态上下文?

转载 作者:行者123 更新时间:2023-11-30 19:57:36 25 4
gpt4 key购买 nike

我有以下类(class):

public class HandleResourceReferencesParams
{
public Factory Factory { get; set; }
public DataObject Resource { get; set; }
public HandleAction Action { get; set; }

public enum HandleAction
{
Activate,
Disable,
Terminate
}
}

在以下代码中使用:

var parameters = new HandleResourceReferencesParams();
parameters.Factory = context.Factory;
parameters.Resource = resource;
parameters.Action = parameters.HandleAction.Terminate; // Does not compile
HandleResourceReferences(parameters);

通过使用 parameters.HandleAction,我得到一个编译错误:

Cannot access static enum 'HandleAction' in non-static context

枚举显然没有声明为“静态”。为什么它在从对象实例(非静态的)引用时具有静态上下文?

编辑:我已经找到了 Tim 提到的解决方案(顺便感谢)。我只是想了解为什么会出现此错误。

最佳答案

错误消息很不幸,但你不能并不不幸......你正在尝试访问一个类型的成员,而不是的成员类型的>实例,但您是“通过”实例这样做的。

基本上,这段代码编译失败的原因是一样的:

Thread t = new Thread(...);
t.Start();
t.Sleep(1000); // Nope, Sleep is a static method

所有 嵌套类型实际上都是静态成员,因为您不能拥有特定于包含类型实例的类型。

来自 C# 规范,第 10.3.7 节(强调我的):

When a field, method, property, event, operator or constructor declaration includes a static modifier, it declares a static member. In addition, a constant or type declaration implicitly declares a static member.

所以枚举是类型的静态成员,尽管没有 static 修饰符。

关于c# - 为什么对象实例中的枚举具有静态上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29251330/

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