You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Visual Studio Community学C#:能否动态命名wordN格式字符串变量?

如何在C#中实现类似动态命名字符串的需求

嘿,我完全get到你想要做的事——每次调用方法就生成一个像word0、word1这样命名的字符串变量,还能自动递增编号,之后再把这些变量存入数组对吧?

首先得明确一点:在C#这种静态类型语言里,没法在运行时动态创建新的命名变量。因为变量名是编译时就确定的,程序运行起来后不能凭空冒出一个新的wordN变量。不过别担心,我们可以用其他方式实现和你需求等价的效果,而且比动态命名变量更规范好用。

方案1:用List(最推荐)

既然你最终要把这些字符串存入数组,那用List<string>是最直接的选择——List的索引正好对应你想要的wordcount编号,比如list[0]就相当于你想要的word0,list[1]对应word1,完美匹配你的需求逻辑:

// 在类里定义两个成员:计数器和存储字符串的列表
private int _wordCount = 0;
private List<string> _words = new List<string>();

// 你的创建方法
public void CreateAndAddWord(string wordValue)
{
    // 把字符串添加到列表,此时_words[_wordCount]就对应"word"+_wordCount的逻辑
    _words.Add(wordValue);
    // 计数器自增,下次调用就对应下一个编号
    _wordCount++;
}

// 转成数组(你已经掌握这一步,这里补充示例)
public string[] GetWordArray()
{
    return _words.ToArray();
}

使用的时候就像这样:

CreateAndAddWord("Hello"); // 对应word0,即_words[0]
CreateAndAddWord("World"); // 对应word1,即_words[1]
string[] wordArray = GetWordArray();

方案2:用Dictionary<string, string>(如果需要通过"wordN"字符串访问)

如果你确实需要通过类似"word0"这样的字符串来访问对应的内容,那可以用字典来映射名称和字符串值:

private int _wordCount = 0;
private Dictionary<string, string> _wordDict = new Dictionary<string, string>();

public void CreateAndAddWord(string wordValue)
{
    string variableName = $"word{_wordCount}";
    _wordDict.Add(variableName, wordValue);
    _wordCount++;
}

// 访问示例
public string GetWordByName(string name)
{
    if (_wordDict.TryGetValue(name, out string value))
    {
        return value;
    }
    return null; // 或者抛出异常,根据你的需求处理
}

调用时:

CreateAndAddWord("测试1");
string word0 = GetWordByName("word0"); // 拿到"测试1"

为什么不推荐动态命名变量?

除了C#本身不支持之外,动态命名变量会让代码变得难以维护——你没法在编译时检查这些变量是否存在,也没法轻松地遍历、批量操作它们。而用List或Dictionary,你可以很方便地做遍历、计数、修改等操作,完全满足你的需求,还更符合C#的编码规范。

内容的提问来源于stack exchange,提问作者Mimimi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:22:39