如何将函数放在其他cs文件中? [英] How can I put functions in other cs file?

查看:160
本文介绍了如何将函数放在其他cs文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C / C ++中,我可以创建一个文件并将所有函数放在此文件中。

In C/C++, I can create a file and put all functions in this file.

lib.h

void plus(int i, int j);

lib.cpp

#include "lib.h"

void plus(int i, int j)
{
    printf("%d\n", i+j);
}

main.cpp
$ b

main.cpp

#include "lib.h"
main()
{
    plus(1, 2);
}

但在C#中,如何将函数放在其他 cs 文件并将其包含在 main.cs

But in C#, How can I put functions in other cs file and include it in main.cs?

推荐答案

首先,你不应该真的这样做。在C / C ++世界中,这是因为您不能使用稍后在程序中声明的函数。

First off, you shouldn't really be doing this. In the C/C++ world this is done because you can't use functions declared later on in the program.

此外,头文件也作为操作系统或某些供应商的共享库的接口。

Also header files serve as an interface to shared libraries on your OS or from some vendor.

@Tigran说是C#中同一个主体的等效

So what @Tigran says is the equivalent of the same principal in C#. You declare an iterface.

如果你真的想在字面意义上要求你使用部分函数。我把它放在任何人好奇。这个目的是为了与C / C ++不同,所以你需要评估你是否真的想这样做,我想你不这样做。

If you really wanted to do what you're asking in the literal sense you could use partial functions. I'm putting it here for anyone curious. The purpose this was designed for is different from C/C++ so you will need to evaluate whether you really want to do this, I think you don't.

请执行此操作,查看msdn了解更多

namespace PM
{
    partial class A
    {
        partial void OnSomethingHappened(string s);
    }

    // This part can be in a separate file. 
    partial class A
    {
        // Comment out this method and the program 
        // will still compile. 
        partial void OnSomethingHappened(String s)
        {
            Console.WriteLine("Something happened: {0}", s);
        }
    }
}

这篇关于如何将函数放在其他cs文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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