0

我想给一个对象一个一直在变化的名字。我有一个 foreach,我在其中设置了一个图钉。每次通过 foreach 循环时,我都希望根据我的列表中的内容有一个新名称(我正在遍历我的列表)。

例如,这是我的代码:

Test test = new Test();
        foreach (var test in Test.allTests)
        {
            Pushpin pushpin = new Pushpin();
        }

我想做这样的事情:

   Test test = new Test();
            foreach (var test in Test.allTests)
            {
                Pushpin test.testname = new Pushpin();
            }

我无法做到这一点,因为 test.testname 是一个字符串..

4

1 回答 1

1

我将在这里伸出我的脖子,对你真正想要的东西做出一些疯狂的假设。

class Pushpin
{
    public Pushpin() { }
    // More Pushpin-related members and methods here
}
class Test
{
    public Test(string name) { Name = name; }
    public string Name { get; set; }
    // More Test-related members and methods here
}
class SO23174064
{
    Dictionary<string, Pushpin> pushpins = new Dictionary<string, Pushpin>();
    public Dictionary<string, Pushpin> CreatePushpins(IEnumerable<Test> tests)
    {
        foreach (Test test in tests)
            pushpins[test.Name] = new Pushpin();
        return pushpins;
    }
}

然后在你的主程序中你可以使用这样的东西:

    Test[] tests = new Test[] { new Test("x"), new Test("y") };
    Dictionary<string, Pushpin> pins = new SO23174064().CreatePushpins(tests);
    // use pins["x"] etc here

我接近了吗?

于 2014-04-19T19:22:08.123 回答