.net 枚举是引用类型还是值类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14561338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Enum is Reference Type or Value Type?
提问by Jon Skeet
I used Enum property in my EntityFramework5 class, but in the database this field is nullable. Visual studio gives the error that this property must be a nullable property. My question is: is Enum a reference type or a value type?
我在EntityFramework5 类中使用了 Enum 属性,但在数据库中该字段可以为空。Visual Studio 给出了此属性必须是可为空属性的错误。我的问题是:枚举是引用类型还是值类型?
回答by Jon Skeet
System.Enumis a reference type, but any specificenum type is a value type. In the same way, System.ValueTypeis a reference type, but all types inheriting from it (other than System.Enum) are value types.
System.Enum是引用类型,但任何特定的枚举类型都是值类型。同样,,System.ValueType是引用类型,但从它继承的所有类型(除了System.Enum)都是值类型。
So if you have an enum Fooand you want a nullable property, you need the property type to be Foo?.
因此,如果您有一个枚举Foo并且想要一个可为 null 的属性,则需要将属性类型设为Foo?.
回答by fhnaseer
If you do myEnum.SomeValueit will be a value type.
如果你这样做myEnum.SomeValue,它将是一个值类型。
回答by SAm
public enum TestReferenceOrValue
{
one, two, three
}
var a = TestReferenceOrValue.one;
var b = a;
b = TestReferenceOrValue.three;
If enums are by reference, changing baffects aConsole.Write(a);→ oneConsole.Write(b);→ three
如果枚举是通过引用,改变b影响aConsole.Write(a);→ 一Console.Write(b);→ 三
a great online tool for cSharp => http://csharppad.com/
一个很棒的 cSharp 在线工具 => http://csharppad.com/
回答by Eklavyaa
suppose we have enum
假设我们有枚举
public enum eCategory
{
health ,
Weapon
}
and a type of eCategory such as :-
和一种 eCategory 类型,例如:-
eCategory currentcategory;
then currentcategory is of value type
那么 currentcategory 是值类型

