Programatically using a string as object name when

2019-02-06 12:31发布

This is a contrived example, but lets say I have declared objects:

CustomObj fooObj;
CustomObj barObj;
CustomObj bazObj;

And I have an string array:

string[] stringarray = new string[] {"foo","bar","baz"};

How can I programatically access and instantiate those objects using the string array, iterating using something like a foreach:

foreach (string i in stringarray) {
    `i`Obj = new CustomObj(i);
}

Hope the idea I'm trying to get across is clear. Is this possible in C#?

Thanks in advance.

标签: c# oop
8条回答
疯言疯语
2楼-- · 2019-02-06 13:29

@jotte: Thanks alot for that function. I used it and it works! Except that you need to change container.ID by container.Name

Then you just need to use something like (this example is for checkbox, but any type of variable could work):

string Test = "cbACn" + i.ToString(); CheckBox cbTest = (CheckBox)FindControl(Test, gbACSCAT); if (cbTest != null) { cbTest.Checked = true; }

查看更多
在下西门庆
3楼-- · 2019-02-06 13:32

One option is the totally dynamic route, as per this article, where you specify a code block in a string and then compile/run it from within your program

查看更多
登录 后发表回答