Add method to a class from another project

2019-07-25 06:07发布

问题:

Is it possible to add a method to a class from another project?

I have a class:

namespace ProjectLibrary
{
    public class ClassA
    {
        // some methods
    }
}

I want to add a method to save my object in a file, but I don't want to add this method in my project ProjectLibrary because I don't want to add reference to System.IO (I want to use this project for android application and PC application).

Is there a possibility to add a method SaveToFile() usable only in another project? Or create an abstract method in ClassA but define it in other project.

Like this :

using ProjectLibrary;
namespace ProjectOnPC
{
    void methodExample()
    {
        ClassA obj = new ClassA();
        // do sommething
        obj.SaveToFile();// => available only in namespace ProjectOnPC
    }
}

Thank you for help

回答1:

The thing You are looking for is called Extension method:

  • DotNetPerls
  • MSDN link
  • What are Extension Methods?

Code for base class:

namespace ProjectLibrary
{
    public ClassA
    {
        // some methods
    }
}

Extension method:

using ProjectLibrary;
namespace ProjectOnPC
{
    void SaveToFile(this ClassA Obj, string Path)
    {
        //Implementation of saving Obj to Path
    }
}

Calling in Your program:

using ProjectLibrary;
using ProjectOnPc; //if You won't include this, You cannot use ext. method

public void Main(string[] args)
{
    ClassA mObj = new ClassA();
    mObj.SaveToFile("c:\\MyFile.xml");
}


回答2:

You can use extension methods.

Example:

namespace ProjectOnPC
{
    public static void SaveToFile(this Class myClass)
    {
      //Save to file.
    }
}


回答3:

You can create an extension method for this purpose.

Here's an example.
In your ProjectOnPc namespace create a class like this:

public static class ClassAExtension
{
    public static void SaveToFile(this ClassA obj)
    {
        // write your saving logic here.
        // obj will represent your current instance of ClassA on which you're invoking the method.
        SaveObject(obj).
    }
}

You can learn more about extension methods here:
https://msdn.microsoft.com/en-us//library/bb383977.aspx