我想给对象一个名字,这个名字一直在变化。我有一个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是一个字符串..
答案 0 :(得分: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
我关闭了吗?