c#循环遍历枚举的所有字段,从字符串数组中赋值

c#循环遍历枚举的所有字段,从字符串数组中赋值,c#,for-loop,enums,ienumerable,C#,For Loop,Enums,Ienumerable,我正在为web服务构建一个Soap主体,有几十个可选字段 目前我一直在这样处理这些问题: wsSoapBody.OrderType = aMessage[(int)cardCreate.OrderType].ToString(); wsSoapBody.ActivateFlag = Convert.ToInt32(aMessage[(int)cardCreate.ActivateFlag].ToString()); //P-02925; if (aMessage[(int)cardCreate

我正在为web服务构建一个Soap主体,有几十个可选字段

目前我一直在这样处理这些问题:

wsSoapBody.OrderType = aMessage[(int)cardCreate.OrderType].ToString();
wsSoapBody.ActivateFlag = Convert.ToInt32(aMessage[(int)cardCreate.ActivateFlag].ToString()); //P-02925;

if (aMessage[(int)cardCreate.ShipDate].ToString() != ""){
                wsSoapBody.ShipmentDate = Convert.ToDateTime(aMessage[(int)cardCreate.ShipDate].ToString()); //P-02925;
        }

wsSoapBody.ShipmentMethodCard = aMessage[(int)cardCreate.ShipMethodCard].ToString();
wsSoapBody.ShipmentMethodPin = aMessage[(int)cardCreate.ShipMethodPIN].ToString();
您在这些值分配中看到的
CardCreate
是类
CardCreate
中的枚举常量,定义如下:

namespace EvryCardManagement
{
    class CardCreate
    {
        #region Variables

        private DCSSCardCreateType req;
        private DCSSCardCreateResponseType rsp;
        private DCSSCardCreate_V3_0Service stub;

        public string tokenID { get; set; }

        private enum cardCreate
        {
            MsgType = 0,
            MsgVersion = 1,
            WSName = 2,
            ReplyTo = 3,
            SourceSystem = 4,
            Timestamp = 5,
            UniqueMessageID = 6,
            SFDCContext = 7,
            InstitutionID = 8,
            CardNumber = 9,
            Version = 10,
            ProductID = 11,
            AccountNumber = 12,
            CustomerID = 13,
            CustomerNumber = 14,
            EmbossName1 = 15,
            Expiry = 16,
            FeeMonth = 17,
            ChargeAccountNo = 18,
            PINMethod = 19,
            CardFlag = 20,
            AddressTypeCard = 21,
            AddressTypePIN = 22,
            OrderType = 23,
            ActivateFlag = 24,
            ShipDate = 25,
            ShipMethodCard = 26,
            ShipMethodPIN = 27,
            FirstName = 28,
            LastName = 29,
            CardAddress1 = 30,
            CardAddress2 = 31,
            CardAddress3 = 32,
            CardAddress4 = 33,
            CardAddress5 = 34,
            CardAddress6 = 35,
            CardPostCode = 36,
            CardCity = 37,
            CardCountry = 38,
            PINName = 39,
            PINAddress1 = 40,
            PINAddress2 = 41,
            PINAddress3 = 42,
            PINAddress4 = 43,
            PINAddress5 = 44,
            PINAddress6 = 45,
            PINPostCode = 46,
            PINCity = 47,
            PINCountry = 48,
            Validfrom = 49,
            Note = 50,
            MakeCheckStatus = 51,
            EmbossName2 = 52,
            PAmount = 53,
            PAmountLength = 54,
            GKIndicator = 55,
            CreditLimit = 56,
            CardDesignNo = 57,
            ExtPictureID = 58,
            BulkID = 59,
            AccountNo2 = 60
        }
因此,与其像我一直在做的那样一个接一个地处理它们,是否可以通过
wsSoapBody
(在web服务中定义)循环,并从
aMessage
(定义为类似于
string[]aMessage
的数组)中为每个对象获取相应的值

编辑

我有下面的代码要循环,但我想分配给
wsSoapBody
,我被卡住了:

foreach (cardCreate cItem in (cardCreate[])Enum.GetValues(typeof(cardCreate)))
 {
 }
(上述更正是由Steve Lillis提出的,由于冲突被拒绝)

所以我不知道如何给每个元素赋值,比如我想设置的元素

wsSoapBody[cItem].value = aMessage[(int)CardCreate[cItem]` 
或者我也试过:

wsSoapBody[cItem] = aMessage[(int)cItem].ToString();
但是由于缺乏知识,我在使它工作(甚至编译)方面遇到了困难

编辑#2

我还查看了
GetNames
,因为我可能需要这些名称,并尝试:

        foreach (string name in Enum.GetNames(typeof(cardCreate)))

        {
            wsSoapBody[name] = aMessage[(int)name].ToString();
        }
但是我
无法将带[]的索引应用于“DCSSCardCreateType”类型的表达式


谢谢

为什么不将值放在枚举本身上,然后进行枚举

例如,使用
System.ComponentModel
Description
属性,我们可以将该信息添加到枚举本身,例如:

public enum cardCreate
{
  [Description("General Response")]
  MsgType = 0,

  [Description("V2.0")]
  WSName = 2,

  [Description("OmegaMan")]
  ReplyTo = 3,

  [Description("Windows 10")]
  SourceSystem = 4,
}
因此,当我们调用一个特殊方法来枚举枚举时,我们可以从中提取该文本,并在以后适当地使用它,例如:

myextensions.GetEnumValues<cardCreate>()
            .Select (ceEnum => new
                        {
                            Original   = ceEnum,
                            IndexValue = (int)ceEnum,
                            Text       = ceEnum.GetAttributeDescription()
                        })

你看过
Enum.GetValues
了吗?Hi-Jon可能是重复的,是的,我用过
foreach(cardCreate[]中的cardCreate cItem)Enum.GetValues(typeof(cardCreate)){}
但是我不知道如何将值分配给每个元素,例如我想设置
wsSoapBody[cItem].value=aMessage[(int)CardCreate[cItem]
但是我让strouble让它工作起来了我正在编辑这个问题,我发现我不清楚我是否能找到一些方法,但分配值有困难…@CompuChip:我编辑了这个问题和标题,以澄清我有枚举循环,但不知道如何从字符串数组分配值我不知道这是否是这是我想要的确切答案,但是你投入了工作,它可能会满足我的需要,所以谢谢!如果我实现了这一点,我如何通过
wsSoapBody
类循环设置
aMessage[]中的所有值
字符串值数组?@OurManInBananas您需要对实例进行反思,并事先提供一个到枚举的映射,然后您可以收集这些值。是的,这就是我在问题中真正想问的,还是我应该为此问一个新问题?我们有12个类似于
cardCreate
的web服务,它们都有问题是我需要在
wsSoapBody
中设置几十个可选和必填字段,因此我们正在寻找一种方法,对每一个字段重复使用相同的方法…@OurManInBananas我会问一个不同的问题,因为它会让您自由地进行针对最终答案的非法响应。
public static class myextensions
{
   public static IEnumerable<T> GetEnumValues<T>()
   {
       Type type = typeof( T );

       if (!type.IsEnum)
           throw new Exception( string.Format("{0} is not an enum.", type.FullName ));

       FieldInfo[] fields =
           type.GetFields( BindingFlags.Public | BindingFlags.Static );


       foreach (var item in fields)
           yield return (T)item.GetValue( null );
   }


  /// <summary>If an attribute on an enumeration exists, this will return that
   /// information</summary>
   /// <param name="value">The object which has the attribute.</param>
   /// <returns>The description string of the attribute or string.empty</returns>
   public static string GetAttributeDescription( this object value )
   {
       string retVal = string.Empty;
       try
       {
           retVal = value.GetType()
                         .GetField( value.ToString() )
                         .GetCustomAttributes( typeof( DescriptionAttribute ), false )
                         .OfType<DescriptionAttribute>()
                         .First()
                         .Description;

       }
       catch (NullReferenceException)
       {
           //Occurs when we attempt to get description of an enum value that does not exist
       }
       finally
       {
           if (string.IsNullOrEmpty( retVal ))
               retVal = "Unknown";
       }

       return retVal;
   }

}