有没有办法在C#
中写一个独立的功能?我需要一个功能,但我不认为它是任何现有class
的成员,我没有看到任何写作点
public abstract class HolderForFunctionsThatIDontKnowWhereElseToPut
{
MyReturnType MyFuction ( ... ) { ... }
}
答案 0 :(得分:4)
没有。如果没有类/结构,你就不能拥有一个函数。
在类或结构中只能有一个函数(方法)。
请参阅:Why Doesn't C# Implement "Top Level" Methods? (Eric Lippert)
答案 1 :(得分:1)
正如@Habib指出你需要一个方法的'容器',所以你可以这样做:
public static class HolderForFunctionsThatIDontKnowWhereElseToPut
{
public static MyReturnType MyFuction ( ... ) { ... }
}
你可以这样称呼它为例:
public class UseStaticMethods
{
public MyReturnType NewFuction ( ... )
{
...
return HolderForFunctionsThatIDontKnowWhereElseToPut.MyFuction(...);
}
}