将整数设置为枚举变量

时间:2011-02-24 22:05:33

标签: c# enums

我有这个枚举:

public enum IndexType : int
    {
        /// <summary>
        /// The value has not been set.
        /// </summary>
        NotSet = 0,
        /// <summary>
        /// No description available.
        /// </summary>
        _1moUSDLIBORBBA = 1,
        /// <summary>
        /// No description available.
        /// </summary>
        _12moUSDLIBORBBA = 71,
        /// <summary>
        /// No description available.
        /// </summary>
        _3moUSDLIBORBBA = 12,
        /// <summary>
        /// No description available.
        /// </summary>
        _6moUSDLIBORBBA = 13,
        /// <summary>
        /// No description available.
        /// </summary>
        USDPRIMEH15 = 1896,
        /// <summary>
        /// No description available.
        /// </summary>
        USDSIFMAMunicipalSwapIndex = 3,
    }

我想创建这个枚举类型的变量,并将其设置为等于这样的整数:

Data.Indications.IndexType indexType = sm.FloatingComponent.IndexID.Value;

但这不是编译。我该怎么做?

2 个答案:

答案 0 :(得分:0)

C#中的枚举允许转换为int和from int。假设IndexID.Value是一个int,它就像:

一样简单
Data.Indications.IndexType indexType = (Chatham.Web.Data.Indications.IndexType)sm.FloatingComponent.IndexID.Value;

答案 1 :(得分:0)

如果您不确定IndexID的值是什么,请使用以下代码:

        if (sm.FloatingComponent.IndexID.HasValue && Enum.IsDefined(typeof(Data.Indications.IndexType),sm.FloatingComponent.IndexID.Value))
        {
            Data.Indications.IndexType indexType = (Data.Indications.IndexType)sm.FloatingComponent.IndexID.Value;
        }
        else
        {
            Data.Indications.IndexType indexType = IndexType.NotSet; 
        }