如何在Visual Studio中使用C#中其他文件中的类? [英] How to use class from other files in C# with visual studio?

查看:491
本文介绍了如何在Visual Studio中使用C#中其他文件中的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#和 MS visual studio 的新手,我想使用在另一个文件中定义的C#类,但无法正常工作.

I am a newbie of C# and MS visual studio, and I want to use the C# class which defined in another file, but can't get it work.

这是program.cs(为什么我不能重命名该文件?)

Here is the program.cs(and why can't I rename that file ?)

using System;

namespace TestCSharp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Class2 class2 = new Class2();
            // here the IDE will complain that cant find namespace or balabala..
            class2.setValue(10);
            Console.WriteLine(class2.getValue().ToString());
            Console.ReadKey();
        }
    }
}

这是我要在文件Class2.cs中使用的Class2:

And here is the Class2 that I want to use in file Class2.cs:

namespace TestCSharp2
{
    class Class2
    {
        int i;
        public void setValue(int i)
        {
            this.i = i;
        }
        public int getValue()
        {
            return this.i;
        }
    }
}

我应该#include还是什么? use namespace还不够吗?

Should I #include or something? isn't use namespace enough?

正如有些人问他们是否在同一程序集/同一项目中一样,我假定,因为这是创建它们的过程:

As some guys asked if they are in the same assembly/same project, I presume they were, because here is the procedure how they are created:

  • 使用 Console C#Project 模板的新项目,然后默认创建program.cs.
  • 使用[文件]-> [新建]-> [文件]-> [C#类]创建Class2.cs,并将其保存在program.cs所在的文件夹中.
  • A new project using the template of Console C# Project, then the program.cs was created by default.
  • The Class2.cs was created with [File] -> [New] -> [File] -> [C# class] and saved in the same folder where program.cs lives.

说实话,我不知道它们是否在相同的程序集/相同的项目中,但是我想它们是相同的.

To be honest, I don't know if they are in same assembly / same project, but I guess they were.

推荐答案

根据您的解释,您没有在项目中包含Class2.cs.您刚刚创建了所需的Class文件,但尚未将其包含在项目中.

According to your explanation you haven't included your Class2.cs in your project. You have just created the required Class file but haven't included that in the project.

Class2.cs是使用[文件]-> [新建]-> [文件]-> [C#类]创建的,并保存在program.cs所在的文件夹中.

The Class2.cs was created with [File] -> [New] -> [File] -> [C# class] and saved in the same folder where program.cs lives.

执行以下操作以克服这一点,

Do the following to overcome this,

在项目上仅Right click,然后-> [添加]-> [现有项目...]:选择Class2.cs并按OK

Simply Right click on your project then -> [Add] - > [Existing Item...] : Select Class2.cs and press OK

现在应该解决问题.

此外,在添加新类时,请使用此过程,

Furthermore, when adding new classes use this procedure,

Right click在项目上-> [添加]->选择必填项(例如,类,表单等)

Right click on project -> [Add] -> Select Required Item (ex - A class, Form etc.)

这篇关于如何在Visual Studio中使用C#中其他文件中的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆