我正在上 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;
}
}
}