简体   繁体   中英

c# Main Class include “subclass”

Hey I have two classes

class Main
{
    public exLog exLog;
    public Main()
    {

    }
}

and

class exLog
{
    public exLog()
    {

    }
    public exLog(String where)
    {

    }
    public exLog(String where, String message)
    {

    }
}

i tried to call exLog direct without giving exLog a parameter. So I can call any class with the Main Method. How should I do that?

public String ReadFileString(String fileType, String fileSaveLocation)
{
    try
    {
        return "";
    }
    catch (Exception)
    {
        newMain.exLog("", "");
        return null;
    }
}

I like to call them like a funtion in Main

You can call it as soon as you instantiate it.

public Main()
{
    exLog = new exLog();
    exLog.MethodInClass();
}

Also, if you are not in the same assembly you'll need to make exLog public.

Finally, this is C# and the style dictates that class names should be PascalCased. It's a good habit to form.

I think you're confused about classes, instances, constructors, and methods. This does not work:

newMain.exLog("", "");

because exLog in this case is a property , not a method . (It's confusing because you use the same name for the class and the property, which is why most conventions discourage that).

You can call a method on the instance :

newMain.exLog.Log("", "");

but then you'll need to change the names of the methods (and add a return type) in your exLog class so they don't get interpreted as constructors:

class exLog
{
    public void Log() 
    {
    }
    public void Log(String where)
    {
    }
    public void Log(String where, String message)
    {
    }
}

Methinks you want something like Adapter Pattern

class Main
{
    private exLog exLog;
    public Main()
    {

    }

    public void ExLog()
    {
        exLog = new exLog();
    }
    public void ExLog(String where)
    {
        exLog = new exLog(where);
    }
    public void ExLog(String where, String message)
    {
        exLog = new exLog(where, message);
    }
}
class Main
{
    public exLog exLog;
    public Main()
    {
        exLog = new exLog();
        exLog.ReadFileString("", "");
    }
}

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