[英]How can I split my code (c#) in Visual Studio while maintaining full functionality?
我意识到这听起来像是一个可以在第一个谷歌链接中找到答案的问题,但令我惊讶的是事实并非如此。 最近在学习C#,第一次写一个比较大的项目,目前有200多行代码,估计最后应该有1000多行。
我知道这对有经验的程序员来说不是问题,但我开始感到困惑。我找到了一些关于从相邻文件中提取类的答案,但我的代码几乎完全由方法组成,我无法解释这些回答我的优势。 同样,这很可能是由于我缺乏经验。
我希望我的文件看起来像这样:
程序1.cs
int x = 25;
程序2.cs
Console.Write(x);
如您所见,这不会发生。 我尝试手动或通过解决方案资源管理器添加 CS 文件。 没有任何帮助,所以我真的希望在这里得到答案。 如何从一个文件中获取所有方法和变量以在 VS 中的另一个文件中工作? 附加问题:如果根本没有这种可能性,我能以某种方式从视觉上隐藏我自己的一段代码,这样它就不会打扰我,直到我需要更改其中的某些内容吗?
PS 是的,我明白如果在代码中很容易混淆,那么代码就很糟糕。 我也在朝这个方向努力,但还是很想知道答案。
如果您的 class 太大,您想将其拆分为多个文件,您可能还应该将其拆分为多个类,每个类执行更简单的工作。 要从另一个 class 访问一个 class 的公共方法和变量,要么它们需要是 static(意味着基本上只有一个),在这种情况下,您可以使用 class 的名称激活它们,例如:
Class1.cs
public static int x = 25;
Class2.cs
Console.Write( Class1.x );
或者您需要引用该 class 的特定实例,例如
Class1.cs
public int x = 25;
Class2.cs
Class1 instance = new Class1();
Console.Write( instance.x );
好的,这是我承诺的代码。
这是我创建的两个文件
程序.cs
using System;
namespace splitClass
{
// You can either write a class here and use it on the other file
public class HelloThere
{
public HelloThere()
{
Console.WriteLine("Hello, there");
}
public static int add(int a, int b)
{
return a + b;
}
public int subtractFromTen(int c)
{
return 10 - c;
}
static void Main(string[] args)
{
// You can also use the class in the other file
UseHelloThere useHelloThere = new UseHelloThere();
Console.WriteLine(useHelloThere.add(8, 9));
}
}
// or split a class into two using partial keyword
public partial class SomeOtherClass
{
public int abc;
public SomeOtherClass()
{
abc = 87;
}
public int getAbc()
{
return abc;
}
public int add(int b)
{
return b + abc;
}
}
}
其他文件.cs
using System;
namespace splitClass
{
// since namespaces are same, you can use the other class from the same file
public class UseHelloThere
{
HelloThere hello;
public UseHelloThere()
{
hello = new HelloThere();
}
public int add(int a, int b)
{
return HelloThere.add(a, b);
}
}
// or you can write the continuation of the other class
public partial class SomeOtherClass
{
public int subtract(int a)
{
return abc - a;
}
}
}
如果你想在VS中让一个文件中的所有方法和变量在另一个文件中工作,你可以参考以下步骤:
首先,在 Program1.cs 中定义变量和方法,例如:
namespace ConsoleApp7
{
namespace ConsoleApp
{
public static class Program1
{
static void Main(string[] args)
{
}
public static int x = 25;
public static void add()
{
x++;
}
}
}
}
最后在Program2.cs中添加using,就可以使用Program1.cs中定义的变量和方法了。
using ConsoleApp7.ConsoleApp;
class Program2
{
static void Main(string[] args)
{
Console.WriteLine(Program1.x);
Program1.add();
Console.WriteLine(Program1.x);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.