Add method to a class from another project

让人想犯罪 __ 提交于 2019-12-11 04:47:51

问题


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



来源:https://stackoverflow.com/questions/40802473/add-method-to-a-class-from-another-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!