c# - 为什么我的 C# 枚举不起作用?

标签 c# casting enums

我在 C# 中遇到枚举问题

我这里有一个枚举:

namespace Project.Shared
{
    public enum CostType
    {
        Dollars,
        Percent
    }
}

我有一个对象试图在这里使用枚举:

using Project.Shared;
namespace Project.Shared.FooNamespace
{
    public class Foo
    {
        public int CostType { get; set; }

        public Foo()
        {

            CostType = (int)CostType.Dollars; // <--- error syntax highlighting on 'Dollars'
        }
    }
}

这会导致错误:

'int' does not contain a definition for 'Dollars' and no extension method 'Dollars' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)

我不明白为什么我不能在那里使用我的枚举。谁能帮我解释一下?

最佳答案

因为你的类 Foo 有这个定义 - public int CostType { get;放; } - 比您的 enum 具有更多的本地范围。

尝试使用它的命名空间完全限定它:

CostType = (int)Project.Shared.CostType.Dollars;

关于c# - 为什么我的 C# 枚举不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8620246/

相关文章:

c# - EF7 一对多映射

c# - LINQ to SQL 和空值

c# - 尝试转换 IEnumerable 时出现异常?

python - 将非整数成员值添加到 Python3 中的 IntEnum

java - 如何在不接收重复项的情况下随机化一定数量的枚举值?

enums - 枚举频率 - 错误 UndefinedFunctionError

c# - 从右到左 DatagridviewCell

c# - 当我不将 .Save() 的位图 .Dispose() 到 MemoryStream 时,为什么会发生内存泄漏?

casting - 转换为未调整大小的类型 : `std::io::Stdout` as `std::io::Write` error

c - 不应在指针类型和整数类型之间执行强制转换