简体   繁体   English

c#Main Class包含“子类”

[英]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. 我试图直接给exLog打电话而不给exLog一个参数。 So I can call any class with the Main Method. 因此,我可以使用Main方法调用任何类。 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 我喜欢称它们为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. 另外,如果您不在同一程序集中,则需要将exLog公开。

Finally, this is C# and the style dictates that class names should be PascalCased. 最后,这是C#,样式指示类名称应为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 . 因为exLog在这种情况下是属性 ,而不是方法 (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: 但是然后您需要在exLog类中更改方法的名称(并添加返回类型),以使它们不会被解释为构造函数:

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

Methinks you want something like Adapter Pattern Methinks,你想要像适配器模式这样的东西

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("", "");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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