Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 给出变量字符串的对象名_C#_String_Object_Foreach_Objectname - Fatal编程技术网

C# 给出变量字符串的对象名

C# 给出变量字符串的对象名,c#,string,object,foreach,objectname,C#,String,Object,Foreach,Objectname,我想给一个对象一个一直在变化的名称。我有一个foreach,里面有一个图钉。每次通过foreach循环时,我希望根据列表中的内容有一个新名称(我正在循环我的列表) 例如,这是我的代码: Test test = new Test(); foreach (var test in Test.allTests) { Pushpin pushpin = new Pushpin(); } 我想这样做: Test test = n

我想给一个对象一个一直在变化的名称。我有一个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[] tests = new Test[] { new Test("x"), new Test("y") };
    Dictionary<string, Pushpin> pins = new SO23174064().CreatePushpins(tests);
    // use pins["x"] etc here

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

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

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;
    }
}
类图钉
{
公共图钉(){}
//这里有更多与图钉相关的成员和方法
}
课堂测试
{
公共测试(字符串名){name=name;}
公共字符串名称{get;set;}
//这里有更多与测试相关的成员和方法
}
SO23174064类
{
字典图钉=新字典();
公共字典创建图钉(IEnumerable测试)
{
foreach(测试中的测试)
图钉[test.Name]=新图钉();
返回销;
}
}
然后在主程序中,您可以使用以下内容:

   Test test = new Test();
            foreach (var test in Test.allTests)
            {
                Pushpin test.testname = new Pushpin();
            }
    Test[] tests = new Test[] { new Test("x"), new Test("y") };
    Dictionary<string, Pushpin> pins = new SO23174064().CreatePushpins(tests);
    // use pins["x"] etc here
Test[]tests=newtest[]{newtest(“x”),newtest(“y”)};
字典销=新的SO23174064()。创建图钉(测试);
//在此处使用引脚[“x”]等

我接近了吗?

有什么特别的原因说明
字典在这里不合适吗?你能解释一下你想用“这样的东西”来完成什么吗?什么类型是
test
,您想将
testname
设置为什么?您想实现什么?您能展示一下您的类
test
Pushpin
的代码吗?这没有多大意义,局部变量名就是这样,它不会以任何方式影响对象。那么,动态变量名对您有什么帮助呢?