问题描述
我已经编写了以下代码,并且编译成功.
I have written below code and it's compiling successfully.
class Program
{
enum Fruits
{
Apple,
Mango,
Banana
}
static void Main(string[] args)
{
Fruits f = new Fruits();
}
}
尽管 Fruits
是 enum
,但编译器和解释器允许我编写此代码.这是否意味着我可以为枚举创建构造函数?如果是,那怎么办?
Despite of Fruits
being an enum
, compiler and interpreter are allowing me to write this. Does this mean I can create a constructor for an enum? if yes then how?
推荐答案
不,你不能.
new Fruits()
将返回默认值(对应于枚举的基础类型中 0
的值),它与 default(水果)
(或您的案例中的 Fruits.Apple
).
new Fruits()
will return the default value (the value corresponding to 0
in the underlying type of the enum), it's the same as default(Fruits)
(or Fruits.Apple
in your case).
请记住,枚举仅是原始类型(默认情况下为 int
)的包装.您几乎可以将 new Fruits()
与 new int()
进行比较.
Remeber that enums are only wrappers around a primitive type (int
by default). You can pretty much compare new Fruits()
to new int()
.
通常,您不使用 new Fruits()
/ new int()
语法,因为通常只写 0
或 default(T)
,但您可能需要在通用代码中使用它.例如:
Usually you don't use the new Fruits()
/new int()
syntax as it's more common to just write 0
or default(T)
, but you may want to use it in generic code. As an example:
public T NewInstance<T>()
where T : new()
{
return new T();
}
允许您调用 NewInstance< Fruits>()
,这将返回 Fruits.Apple
.
You are allowed to call NewInstance<Fruits>()
, which will return Fruits.Apple
.
这篇关于我可以为Enum创建构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!