[英]How to call a method of other class from Static void main in c# console application?
我想從PRogram
類調用GetDataTabletFromCSVFile
方法,但是當我嘗試創建ReadCSV
類的實例時,我收到此錯誤: Type or name space could not be Found
這是我的代碼如下:
class Program
{
static void Main(string[] args)
{
ReadCSV r = new ReadCSV();
}
}
public class ReadCSV
{
//reading data from CSV files
public static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
}
}
C#中的static
關鍵字完全改變了您聲明它的類型/成員的行為。
使用static修飾符聲明一個靜態成員,該成員屬於該類型本身而不是特定對象。
這解釋了static
方法如何在調用之前不需要聲明實例。 考慮它的一個簡單方法是static
而是使用type
聲明作為namespace
而不是object
成員。
下面的代碼可用於實現您想要的結果:
class Program
{
static void Main(string[] args)
{
//Using command line arguments here would be a good idea.
string path = "Some/Random/Directory/File.csv";
var dataTable = ReadCSV.GetDataTabletFromCSVFile(path);
//Now do something with dataTable...
}
}
//It would be a good idea to declare the class as static also.
public static class ReadCSV
{
//reading data from CSV files
public static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
//You will also need to return something here.
}
}
您不需要為靜態方法創建實例。 您可以使用類名本身直接訪問靜態成員。
class Program
{
static void Main(string[] args)
{
DataTable Tbl = ReadCSV.GetDataTabletFromCSVFile(path);
}
}
public class ReadCSV
{
//reading data from CSV files
public static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
}
}
你必須聲明靜態類ReadCSV。 要使用靜態方法,其類必須是靜態的
public static class ReadCSV
{
//reading data from CSV files
public static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
//You will also need to return something here.
}
}
在主要的
class Program
{
static void Main(string[] args)
{
DataTable Tbl = ReadCSV.GetDataTabletFromCSVFile(path);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.