为什么对象实例中的枚举具有静态上下文? [英] Why an enum in an object instance has a static context?
问题描述
我有以下类:
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
,我得到一个编译错误:
By using parameters.HandleAction
, I get a compile error:
在非静态上下文中无法访问静态枚举HandleAction
Cannot access static enum 'HandleAction' in non-static context
枚举显然不声明为静态。为什么从对象实例(非静态)引用静态上下文?
The enum is clearly not declared 'static'. Why does it have a static context when it is referenced from an object instance (non static as well)?
编辑:
我已经找到了Tim提到的解决方案(感谢方式)。我只是想了解为什么我得到这个错误。
I already found the solution mentioned by Tim (Thanks by the way). I am just trying to understand why I am getting this error.
推荐答案
错误信息是不幸的,但不幸的是,不能做它...您正在尝试访问类型的成员,而不是类型的实例的成员,但您正在做所以通过一个实例。
The error message is unfortunate, but it's not unfortunate that you can't do it... you're trying to access a member of a type, rather than a member of an instance of the type, but you're doing so "via" an instance.
基本上,这个代码无法编译的原因相同:
Basically, it's the same reason that this code fails to compile:
Thread t = new Thread(...);
t.Start();
t.Sleep(1000); // Nope, Sleep is a static method
所有嵌套类型有效静态成员,因为您不能具有特定于包含类型实例的类型。
All nested types are effectively static members, in that you can't have a type which is specific to an instance of the containing type.
从C#规范,第10.3.7节(强调我的):
From the C# spec, section 10.3.7 (emphasis mine):
当字段,方法,属性,事件,操作符或构造函数声明包含一个
static
修饰符,它声明一个静态成员。 此外,常量或类型声明隐式声明一个静态成员。
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
修饰符。
So the enum is a static member of the type, despite not having the static
modifier.
这篇关于为什么对象实例中的枚举具有静态上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!