【问题标题】:get object type and assign values accordingly获取对象类型并相应地分配值
【发布时间】:2014-07-31 16:58:06
【问题描述】:

我有一个数组列表,其中包含 不同类型的值,第一个值->字符串,第二个值-> 日期时间,第三个value--> boolean 和第四个值是 int,我如何找到他们的类型并相应地分配这些值,感谢任何帮助:)

这是我的代码:

foreach (object obj in lstTop)
            {

              if(obj.GetType() == string)
                {do this...)
              else if(obj.GetType() == DateTime)
                {do this....}
              else if(obj.GetType() == bool)
                {do this....}
              else if(obj.GetType() == Int)
                {do this....}
            }

谢谢大家,我的最终代码:

string Subscription = "";
        DateTime issueFirst;
        DateTime issueEnd;

        foreach (object obj in lstTop)
        {
            ///Type t = obj.GetType();
            if (obj is string)
                Subscription += obj + ",";
            else if (obj is DateTime)
            {
               Subscription += Convert.ToDateTime(obj).ToShortDateString() + ",";
            }
           /// else if (t == typeof(DateTime))                
        }
    return ("User Authenticated user name: " + userName + ", Subscription: " + Subscription);

【问题讨论】:

  • 在类型前面添加 typeof(),例如类型(字符串),类型(日期时间)。
  • '2.0' 本身是一个非常糟糕的标签选择。今后请多注意问题的自动提示提示:正确的标记是合格的人如何找到您的问题。
  • 如果可以,请摆脱这种情况。数组列表是表示四元组数据的糟糕方式。考虑定义一个包含这四个数据的自定义类并改用它。

标签: c# .net .net-2.0


【解决方案1】:
foreach (object obj in lstTop)
        {

          if(obj is string)
            {do this.....}
          else if(obj is DateTime)
            {do this.....}
          else if(obj is bool)
            {do this.....}
          else if(obj is Int)
            {do this.....}
          else
          {
              // always have an else in case it falls through
              throw new Exception();
          }
        }

【讨论】:

    【解决方案2】:

    .Net 2.0 中的 ArrayLists 几乎总是错误的方法。即使您不知道该列表将包含什么,您最好还是使用通用的List<Object>,因为这会向其他人传达该列表确实可以包含任何内容,而不仅仅是 .Net 1.1 程序员的遗留物.

    除此之外,is 关键字应该可以满足您的需求:

    if (obj is string)
        // do this
    else if (obj is DateTime)
        // do this
    // ...
    

    更新我知道这是旧的,但它出现在我今天的通知中。再读一遍,我想到另一个很好的方法是通过重载函数的类型解析:

    void DoSomething(string value) { /* ... */ }
    void DoSomething(DateTime value) { /* ... */ }
    
    DoSomething(obj);
    

    【讨论】:

    • “但除此之外,林肯夫人……”
    【解决方案3】:

    最简单的解决方案是不使用循环,因为您确切知道列表中的内容。

    string   myString = (string)   lstTop[0];
    DateTime myDate   = (DateTime) lstTop[1];
    bool     myBool   = (bool)     lstTop[2];
    int      myInt    = (int)      lstTop[3];
    

    【讨论】:

    • 索引可能不同。并不总是可靠的。
    • 我不建议这样做,因为如果转换失败,直接转换会引发运行时错误。
    【解决方案4】:

    如果您的列表只包含每种类型的一个值,您可以将其存储在 Dictionary 中(如果使用 ArrayList 不是特定要求),只需根据请求的类型检索值:

    private Dictionary<Type, Object> data = GetDataList();
    string myString = (string)data[typeof(string)];
    int myInt = (int)data[typeof(int)];
    

    这将使获取值的过程更加稳健,因为它不依赖于以任何特定顺序出现的值。

    ArrayList 转换成这样一个字典的例子:

    ArrayList data = new ArrayList();
    data.Add(1);
    data.Add("a string");
    data.Add(DateTime.Now);
    
    Dictionary<Type, Object> dataDictionary = new Dictionary<Type, object>();
    for (int i = 0; i < data.Count; i++)
    {
        dataDictionary.Add(data[i].GetType(), data[i]);
    }
    

    【讨论】:

      【解决方案5】:

      我将有一个封装每种数据类型的抽象类,而不是使用原始类型。然后,处理该类型的逻辑可以嵌入到类本身中。

      foreach( MyBaseData data in lstData )
      {
          data.DoTheRightThing();
      }
      

      一般来说,任何切换对象类型的代码都应该被视为设计异味 - 它不一定是错误的,但最好再看看它。

      虽然编写一个类来封装一个简单类型可能感觉是不必要的工作,但我认为我从来没有后悔过这样做。

      【讨论】:

      • 为简单类型创建扩展方法可能比封装每个方法更容易。
      【解决方案6】:

      只是一些更简洁的代码:

      foreach (object obj in lstTop)
              {
      
                if(obj is string)
                  {do this...)
                else if(obj is DateTime)
                  {do this....}
                else if(obj is bool)
                  {do this....}
                else if(obj is int)
                  {do this....}
              }
      

      如果你的数组总是在同一个位置有相同的对象,只需索引到数组并进行直接转换。

      【讨论】:

        【解决方案7】:
                foreach (object obj in lstTop)
                {
        
                  if(obj.GetType() == typeof(string))
                    {do this...)
                  else if(obj.GetType() == typeof(DateTime))
                    {do this....}
                  else if(obj.GetType() == typeof(bool))
                    {do this....}
                  else if(obj.GetType() == typeof(int))
                    {do this....}
                }
        

        GetType 方法返回对象的System.Type。因此,您需要将其与另一个 System.Type 进行比较,后者是您使用 typeof 获得的。

        【讨论】:

          猜你喜欢
          • 2016-11-20
          • 2020-06-26
          • 2021-08-04
          • 1970-01-01
          • 1970-01-01
          • 2021-08-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多