简体   繁体   中英

How to call a method of other class from Static void main in c# console application?

I want to call the GetDataTabletFromCSVFile method from the PRogram class, but when I try to create an instance of the ReadCSV class, I am getting this error: Type or name space could not be Found

Here is my code below:

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) 
    {

    }
}

The static keyword in C# entirely changes the behavior of the type/member you are declaring it with.

Below is from the Microsoft .NET Documentation.

Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object.

This explains how static methods don't require an instance to be declared before they are called. An easy way to think about it is that static is instead using the type declaration as a namespace rather than an object member.

The code below could be used to achieve the results you desire:

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.
    }
}

You don't need to create an instance for static methods. You can directly access the static members by using the class name itself.

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)
    {

    }
}

you must declare static class ReadCSV. to use static method, its class must be static

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.
    }
}

and in main

class Program
{
    static void Main(string[] args)
    {
        DataTable Tbl = ReadCSV.GetDataTabletFromCSVFile(path);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM