微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

定义不同types的二维dynamic数组

我想创build两个不同types的数组,像我可以添加到该数组的两个值其中之一是控制名,第二个是布尔值。

检查SuspendLayout

C# – 如何从静态主要方法调用一个方法

孤立的存储误解

开发以pipe理员身份运行命令的应用程序

以编程方式将SSL证书绑定到端口

你不能这样做。 相反,您应该创建一个包含这两个属性的类,然后可以创建该类型的数组:

public class MyClass { public string ControlName {get;set;} public bool MyBooleanValue {get;set;} } public MyClass[] myValues=new MyClass[numberOfItems];

或者,正如Anders所说,如果其中一个属性是用来执行查找的,则可以使用字典。

你不能用数组。

也许你应该使用一个字典 ?

Dictionary<string,bool>一个通用字典似乎是那种可以用于描述的东西。

字典将为你正在尝试做的工作。

Dictionary<string,bool> controllerDictionary = new Dictionary<string,bool>();

设置一个

if (controllerDictionary.ContainsKey(controllerName)) controllerDictionary[controllerName] = newValue; else controllerDictionary.Add(controllerName,newValue);

获得价值

if (controllerDictionary.ContainsKey(controllerName)) return controllerDictionary[controllerName]; else //return default or throw exception

如果你想通过控件名来查找/设置布尔值,你可以使用Dictionary<string,bool> 。

另一种方法是创建一个类型对象的数组,然后将其添加一个数组列表。 这是一些示例代码

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; using System.Collections.Generic; namespace Collections { class Program { static void Main(string[] args) { ArrayList ar = new ArrayList(); object[] o = new object[3]; // Add 10 items to arraylist for (int i = 0; i < 10; i++) { // Create some sample data to add to array of objects of different types. Random r = new Random(); o[0] = r.Next(1,100); o[1] = "a" + r.Next(1,100).ToString(); o[2] = r.Next(1,100); ar.Add(o); } } } }

这取决于你想如何使用你的数组。 你想通过一个键或索引来查找值吗? Konamiman建议上课。 但是有两种类型的类只不过是一个Dictionary<type of key,type of value> 。 如果您想通过键获取值,则可以使用字典。 像这样:

Dictionary<string,int> MyDict = new Dictionary<string,int>(); MyDict.Add("Brutus",16); MyDict.Add("Angelina",22); int AgeOfAngelina = MyDict["Angelina"];

现在字典的缺点是,你不能迭代它。 订单不确定。 你不能使用MyDict[0].Value来获得勃鲁托斯(16岁)的年龄。

你可以使用一个

List<keyvaluePair<string,int>> MyList = new List<keyvaluePair<string,int>>();

迭代通过两个不同类型的二维数组作为List支持迭代。 但是再次,你不能通过MyList["Angelina"].Value获得Angelina的年龄,但是你必须使用MyList[0].Value 。

但是你也可以使用数据表。 但是需要更多的工作来使用列来初始化表格。

使用Dictionary <string,bool>。 如果出于某种原因,你确实需要一个数组,试试object [,]并将其值转换为你想要的类型。

“多维数组是一个数组:所有维度中的所有元素都具有相同的类型”

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐