声明Collection的正确方法是什么?对象和不同数据类型的

本文关键字:对象 数据类型 是什么 Collection bool 声明 方法 | 更新日期: 2023-09-27 18:11:57

如何正确使用Collection对象&不同数据类型的?

我得到type or namespace Collection<bool> could not be found错误。还发现成员变量_isFormData同时是bool、int和string。: -/

看到这个例子,在接受的答案下,在Web API:如何访问多部分表单值时使用MultipartMemoryStreamProvider?

private Collection<bool> _isFormData = new Collection<bool>();  //bool...
_isFormData.Add(String.IsNullOrEmpty(contentDisposition.FileName));  //string...
for (int index = 0; index < Contents.Count; index++)
{
   if (_isFormData[index]) //int...
   { }
}

声明Collection<bool>的正确方法是什么?对象和不同数据类型的

您需要有一个using System.Collections.ObjectModel;行,以便在您的类中正确引用类型。

类型只能是布尔值的集合:

String.IsNullOrEmpty(contentDisposition.FileName)

测试contentDisposition.FileNamenull还是"",如果是则返回true;虚假的否则。

isFormData[index]

返回元素index处集合中的bool值。

下面是一个示例。注意"using System.Collections.ObjectModel"

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
public class Program
{
   public static void Main (String[] args)
   {
       IList<Boolean> testCollection = new Collection<Boolean>();
       testCollection.Add(false);
       testCollection.Add(true);
       FillCollection(testCollection);
       for (int index = 0; index < testCollection.Count; index++)
       {
           if (testCollection[index])
           {
               Console.WriteLine("testCollection[{0}] is true", index);
           }
           else
           {
               Console.WriteLine("testCollection[{0}] is false", index);   
           }
       }
   }
   public static void FillCollection (IList<Boolean> collection)
   {
       Random random = new Random();
       for (int i = 0; i < 500; i++)
       {
           Boolean item = Convert.ToBoolean(random.Next(0, 2));
           collection.Add(item);
       }
   }
}