枚举是参考类型还是值类型?

时间:2022-02-22 04:15:15

I used Enum property in my EntityFramework 5 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?

我在我的EntityFramework 5类中使用了Enum属性,但在数据库中该字段可以为空。 Visual Studio提供了此属性必须是可空属性的错误。我的问题是:Enum是引用类型还是值类型?

4 个解决方案

#1


61  

System.Enum is a reference type, but any specific enum type is a value type. In the same way, System.ValueType is 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 Foo and you want a nullable property, you need the property type to be Foo?.

因此,如果你有一个枚举Foo并且你想要一个可以为null的属性,你需要属性类型为Foo?。

#2


11  

If you do myEnum.SomeValue it will be a value type.

如果你执行myEnum.SomeValue,它将是一个值类型。

#3


7  

public enum TestReferenceOrValue
{
    one, two, three    
}
var a = TestReferenceOrValue.one;
var b = a;
b = TestReferenceOrValue.three;

If enums are by reference, changing b affects a
Console.Write(a); → one
Console.Write(b); → three

如果枚举是通过引用,则更改b会影响Console.Write(a); →一个Console.Write(b); →三

a great online tool for cSharp => http://csharppad.com/

一个很棒的在线工具cSharp => http://csharppad.com/

#4


0  

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是值类型

#1


61  

System.Enum is a reference type, but any specific enum type is a value type. In the same way, System.ValueType is 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 Foo and you want a nullable property, you need the property type to be Foo?.

因此,如果你有一个枚举Foo并且你想要一个可以为null的属性,你需要属性类型为Foo?。

#2


11  

If you do myEnum.SomeValue it will be a value type.

如果你执行myEnum.SomeValue,它将是一个值类型。

#3


7  

public enum TestReferenceOrValue
{
    one, two, three    
}
var a = TestReferenceOrValue.one;
var b = a;
b = TestReferenceOrValue.three;

If enums are by reference, changing b affects a
Console.Write(a); → one
Console.Write(b); → three

如果枚举是通过引用,则更改b会影响Console.Write(a); →一个Console.Write(b); →三

a great online tool for cSharp => http://csharppad.com/

一个很棒的在线工具cSharp => http://csharppad.com/

#4


0  

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是值类型