我意識到這聽起來像是一個問題,答案可以在第一個谷歌鏈接中找到,但令我驚訝的是它不是。我最近在學習 C#,我第一次寫了一個相當大的專案,目前包含 200 多行代碼,根據我的估計,最終應該包含 1000 多行。
我知道這對于有經驗的程式員來說不是問題,但我開始感到困惑。我找到了一些關于從相鄰檔案中提取類的答案,但我的代碼幾乎完全由方法組成,我無法解釋這些回答我的優勢。同樣,這很可能是由于我的經驗不足。
我希望我的檔案看起來像這樣:
程式1.cs
int x = 25;
程式2.cs
Console.Write(x);
如您所見,這不會發生。我嘗試手動或通過解決方案資源管理器添加 CS 檔案。沒有什么幫助,所以我真的希望在這里得到答案。如何從一個檔案中獲取所有方法和變數以在 VS 中的另一個檔案中作業?附加問題:如果根本沒有這種可能性,我能否以某種方式在視覺上隱藏我的一段代碼,以便在我需要更改其中的某些內容之前它不會打擾我?
PS 是的,我理解如果在代碼中很容易混淆,那么代碼撰寫得不好。我也在朝這個方向努力,但我還是想知道答案。
uj5u.com熱心網友回復:
如果您的類太大,您想將其拆分為多個檔案,那么您可能還應該將其拆分為多個類,每個類執行更簡單的作業。要從另一個類訪問一個類的公共方法和變數,它們需要是靜態的(意味著基本上只有一個),在這種情況下,您可以使用類的名稱來激活它們,例如:
Class1.cs
public static int x = 25;
Class2.cs
Console.Write( Class1.x );
或者您需要對該類的特定實體的參考,例如
Class1.cs
public int x = 25;
Class2.cs
Class1 instance = new Class1();
Console.Write( instance.x );
uj5u.com熱心網友回復:
好的,這是我承諾的代碼。
這是我創建的兩個檔案
程式.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;
}
}
}
uj5u.com熱心網友回復:
如果你想從一個檔案中獲取所有方法和變數在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中添加專案參考。

最后在 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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465547.html
上一篇:在JAVA中列印到控制臺
