简体   繁体   中英

How to Import Old code from a Different namespace into My Current Project?

I want to use old code in a new project in c#.

This is the old code. It is saved in an arbitrary folder on my PC.

namespace OldCode{
    class HellowWorld
    {
        public static void SayHello()
        {
            Console.writeline("Hello World")
        }
    }
}

I want to use this in a new project called new code.

using OldCode (?)

namespace NewCode
{
    class SayHelloNew
    {
        HelloWorld.SayHello();
    }
}

My question is, how do I link to my old project? Did I do it right with using OldCode? Or is there some other dependency file I need to set up?

That is almost correct. The colon ( : ) needs to be removed from the namespace declaration and to access the HelloWorld class externally, it must be public.

OldCode\HelloWorld.cs

namespace OldCode
{
    public class HelloWorld
    {
        public static void SayHello()
        {
            Console.writeline("Hello World")
        }
    }
}

NewCode\SayHelloNew.cs

using OldCode;

namespace NewCode
{
    class SayHelloNew
    {
        HelloWorld.SayHello();
    }
}

You will also need to ensure the compiler has access to OldCode on compilation, or, if using Visual Studio, add a Reference to the OldCode project in the NewCode project.

Add references in Visual Studio

Yeap, Let me describe for you,
First you should make public your class to access it in other sources by adding public modifier like this:

using System;
namespace Stackoverflow.OldCode
{
    public class HelloWorld    // <----------- make it public
    {
        public static void SayHello()
        {
            Console.WriteLine("Hello World!!!");
        }
    }
}

Then I suggest adding a prefix in every other namespace s to show they are related to each other, like

namespace Stackoverflow.OldCode;
namespace Stackoverflow.NewCode;

The NewCode project and the OldCode should be in one solution, if not now, right-click on the solution name and choose: Add>New Project... or Add>Existing Project...

添加新项目

Then you should add the NewCode project as a reference to the OldCode project:

step1:

添加参考 step2:

选择旧项目

Now you can access old project methods easily, like:

using Stackoverflow.OldCode;   // <---- add the reference
namespace Stackoverflow.NewCode
{
    class SayHelloNew
    {
        public static void SomeRandomName()
        {
            HelloWorld.SayHello();  // <----- call it 
        }
    }
}

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