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

C#如何实现使用用户输入字符串作为新建对象的变量名

解答

C#是静态编译型语言,所有变量名必须在编译阶段就确定,根本不支持运行时动态生成自定义命名的变量,你写的Human [newMemberName] = new Human(...)的写法没有对应的语法支持,这就是你查了很久资料都找不到实现方式的原因——这条路本身在C#的语言设计里就不存在。

你要实现「用用户输入的字符串作为标识关联、访问对应Human对象」的需求,完全不需要动态变量名,用Dictionary<string, Human>(字符串到Human实例的键值对字典)就能实现完全等价的效果,这也是这类场景的标准实现方式:

  • 字典的Key存用户输入的成员名称
  • 字典的Value存对应的Human对象实例
  • 后续需要访问对应对象时,直接把名字当Key从字典中查询即可

可直接参考以下实现代码:

using System;
using System.Collections.Generic;

// 你的Human类定义
public class Human
{
    public string Name { get; set; }
    public int Level { get; set; }
    public Human(string name, int level)
    {
        Name = name;
        Level = level;
    }
}

class Program
{
    static void Main()
    {
        // 初始化字典,存储所有成员的「名称-对象」映射
        Dictionary<string, Human> memberList = new Dictionary<string, Human>();
        // 你之前写的示例对象也可以存入字典
        Human mihkel = new Human("Mihkel", 1);
        memberList.Add("Mihkel", mihkel);

        Console.WriteLine("Please enter the desired name of the new human member!");
        string newMemberName = Console.ReadLine().Trim();
        
        // 基础输入校验,避免空值、重名导致运行报错
        while (string.IsNullOrWhiteSpace(newMemberName) || memberList.ContainsKey(newMemberName))
        {
            Console.WriteLine("输入名称不能为空,且不能和已有成员重名,请重新输入:");
            newMemberName = Console.ReadLine().Trim();
        }

        // 创建新实例并存入字典,Key就是用户输入的名称
        Human newMember = new Human(newMemberName, 1);
        memberList.Add(newMemberName, newMember);

        // 后续访问该对象时,直接通过名称从字典取值即可
        Human targetMember = memberList[newMemberName];
        Console.WriteLine($"已成功创建成员:{targetMember.Name},当前等级:{targetMember.Level}");
    }
}

额外说明:

  • 如果你看到有人提用反射、动态生成运行时代码的方式实现“动态变量名”,不要去学,这类方案复杂度极高、性能差、维护成本高,对你当前的需求来说完全没有必要,字典是最简单、最高效的选择。
  • 换个思路想,你要动态变量名的核心诉求无非是“能通过用户输入的字符串找到对应的对象”,字典的键值对映射逻辑完全能满足这个诉求,不需要纠结变量名本身是不是和输入的字符串一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 13:57:12