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

C#新手求助:'userInputsGirl'是变量却被当作类型使用的报错问题

解决你的C#编译错误:'userInputsGirl' is a variable but is used like a type

嘿,作为C#初学者遇到这种问题太正常啦,我来帮你拆解一下问题出在哪,以及怎么快速修复:

问题根源分析

你碰到的错误主要来自两个小问题:

  1. 嵌套类的访问限制:你把userInputsGirl定义成了userInputsBoy的内部嵌套类,但你的Main方法属于外部的Program类,直接写userInputsGirl编译器找不到这个类型,它不知道你指的是什么。
  2. 变量名与类名重复:你写了userInputsGirl userInputsGirl = new userInputsGirl();,这里变量名和类名完全一样,编译器会优先把后面的userInputsGirl当成已经声明的变量,而不是类型,所以就抛出了那个报错。

修复方案(推荐第一种,更适合初学者)

方案1:把两个类改成独立的顶级类(最直观的修复)

把userInputsGirl从userInputsBoy的内部移出来,让两个类都作为独立的顶级类,这样在Main里就能直接引用它们了,同时我建议变量名别和类名重复(虽然C#允许,但很容易混淆)。

修正后的类定义:

class userInputsBoy { 
    public string name; 
    public int age; 
    public string personality; 
    public userInputsBoy() { 
        name = ""; 
        age = 0; 
        personality = ""; 
    } 
}

class userInputsGirl { 
    public string name; 
    public int age; 
    public string personality; 
    public userInputsGirl() { 
        name = ""; 
        age = 0; 
        personality = ""; 
    } 
}

修正后的Main方法:

class Program { 
    static void Main(string[] args) { 
        userInputsBoy boyInputs = new userInputsBoy(); // 变量名改成boyInputs,避免和类名重复
        userInputsGirl girlInputs = new userInputsGirl(); // 变量名改成girlInputs
        
        Console.Write("Enter your name in : "); 
        boyInputs.name = Console.ReadLine(); 
        Console.Write("Enter your age here : "); 
        boyInputs.age = Convert.ToInt32(Console.ReadLine()); 
        Console.Write("Enter your personality here : "); 
        boyInputs.personality = Console.ReadLine(); 
        
        // 这里注意girlInputs的name还没赋值哦,如果你想输出女孩的信息,记得也要给它添加输入逻辑~
        Console.WriteLine(girlInputs.name + " " + boyInputs.age + " " + boyInputs.personality); 
    }
}

方案2:保留嵌套类(适合了解嵌套类用法的场景)

如果你确实需要把userInputsGirl作为userInputsBoy的嵌套类,那在声明变量时需要用完整的类名userInputsBoy.userInputsGirl,同时变量名不能和类名重复:

class Program { 
    static void Main(string[] args) { 
        userInputsBoy boyInputs = new userInputsBoy(); 
        userInputsBoy.userInputsGirl girlInputs = new userInputsBoy.userInputsGirl(); // 用完整类名引用
        
        // 后续代码和方案1一致...
    }
}

额外小建议

  • 按照C#的命名规范,类名应该使用帕斯卡命名法(每个单词首字母大写),比如把userInputsBoy改成UserInputsBoy,这样代码可读性会高很多哦~
  • 你现在给girlInputs的name没有赋值,输出的时候会是空字符串,要是需要的话记得也要给它添加输入逻辑呀!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 12:37:47