简体   繁体   中英

How do I add a cs file to an existing C# project?

A while back I wrote a little program in Microsoft Visual C# 2008 Express Edition. In it included a file called "ProblemReport.cs" with it's own form and ProblemReport class.

I'm writing a new program and want to reuse this code. (still working in MS Vis C# 2008 express)

In my new program, in the C# Solution Explorer, I right clicked on my project and chose "Add existing item..." I then added ProblemReport.cs, ProblemReport.designer.cs and ProblemReport.resx.

What step(s) am I missing here? When I go back to the main form in my new program, and try to instantiate a new instance of "ProblemReport", I get the error message:

"The type of namespace name 'ProblemReport' could not be found (are you missing a using directive or an assembly reference?)"

Obviously - I'm supposed to do something else to get this to work... just not sure what it is!

-Adeena

Ensure that all your CS files are within the same namespace. Sounds like the imported one(s) aren't living with your new project.

Ensure that:

namespace MyProgram //same as the rest of your project
{

    public class ProblemReport
    {
    }

}

meanwhile in your other .cs files....

namespace MyProgram 
{

     public class SomeClass
     {
           public void DoSomething()
           {
               ProblemReport. //you should get intellisense here.
           }
      }

}

You might be better off extracting ProblemReport into it's own class library (separate dll) so you only have one copy of the code.

Create a new class library project, copy ProblemReport.cs, ProblemReport.designer.cs and ProblemReport.resx into that and update the namespace as required. Build it and put the dll somewhere central. Then add a reference to this class library from your two programs.

You have to add a "using" directive to your new project -

using ProblemReport;

Then you should be able to access the ProblemReport class. Of course this depends on the name of namespace of the ProblemReport.cs file.

When you created it it's likely it used a different namespace, as those are generated from the project name by default.

In the .CS file does the namespace match that of the rest of your project?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM