将方法添加到另一个项目的类中 [英] Add method to a class from another project

查看:102
本文介绍了将方法添加到另一个项目的类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从另一个项目向类添加方法?

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

我有一堂课

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

我想添加一种将对象保存到文件中的方法,但是我不想在我的项目ProjectLibrary中添加此方法,因为我不想添加对System.IO的引用(我想将此项目用于android应用程序和PC应用程序.

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).

是否可以添加仅在另一个项目中可用的方法SaveToFile()?或在ClassA中创建一个抽象方法,但在其他项目中对其进行定义.

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.

喜欢这个:

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

谢谢您的帮助

推荐答案

您正在寻找的东西称为Extension method:

The thing You are looking for is called Extension method:

  • DotNetPerls
  • MSDN link
  • What are Extension Methods?

基类的代码:

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

扩展方法:

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

调用程序:

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");
}

这篇关于将方法添加到另一个项目的类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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