【发布时间】:2013-10-10 09:47:53
【问题描述】:
我正在学习 C# 在线自学课程,但有一个作业我想不通。 我得到了一个半准备好的应用程序,我需要创建一个类和所有成员才能让它工作。我无法更改“类应用程序”下的任何内容。这是给我的模板:
using System;
namespace ObjectOriented
{
// Your Code Here
class Application
{
static void Main()
{
TypeCollection collection = new TypeCollection(3);
collection["integer"] = 123;
collection["double"] = 456.78;
collection["string"] = "Hello world!";
double sum = (double)(int)collection["integer"] + (double)collection["double"];
Console.WriteLine("The sum of all numbers is {0}", sum);
Console.WriteLine();
TypeCollection collection2 = new TypeCollection(2);
collection2["integer"] = 123;
collection2["double"] = 456.78;
collection2["string"] = "Hello world!";
}
}
}
这是它应该打印的内容:
Added integer = 123
Added double = 456.78
Added string = Hello world!
The sum of all numbers is 579.78
Added integer = 123
Added double = 456.78
Collection is full
我最大的问题是如何创建带有键作为字符串的数组。这是我尝试过的,但我无法让它接受字符串作为键。
public class TypeCollection
{
private object[] colType;
public TypeCollection(object length)
{
this.tyyppi = new object[(int) length];
}
public object this[string key]
{
get
{
return colType[key];
}
set
{
colType[key] = value;
}
}
}
【问题讨论】:
-
使用
Dictionary<string, object>而不是object[] -
您的集合对象不是数组,它 - 正如名称已经适用的那样 - 一个集合。这表示您还可以使用键访问所有集合条目,就像它是一个数组一样,但也可以使用字符串作为键,而不仅仅是索引。
-
创建通用集合,一个用于字符串,一个用于双精度,一个用于整数。
标签: c#