【问题标题】:c# Main Class include "subclass"c#主类包括“子类”
【发布时间】:2015-07-19 14:04:03
【问题描述】:

嘿,我有两门课

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

    }
}

class exLog
{
    public exLog()
    {

    }
    public exLog(String where)
    {

    }
    public exLog(String where, String message)
    {

    }
}

我试图直接调用 exLog 而不给 exLog 一个参数。所以我可以用 Main 方法调用任何类。 我该怎么做?

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

我喜欢将它们称为 Main 中的函数

【问题讨论】:

  • 阅读课程和Constructors。第一类中的Main 是构造函数,以便其他类中的其他方法
  • public exLog exLog = new exLog(); 旁注 - 类名应以大写字母开头(字段以小写字母开头) - 这是相当普遍的约定。
  • @DStanley 在 C# 中相当普遍:)。
  • @DStanley 这个公开的 exLog exLog = new exLog();会说我只能调用 1 个构造函数,但我喜欢从另一个类调用这 3 个构造函数中的任何一个

标签: c# call mainclass


【解决方案1】:

一实例化就可以调用它。

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

另外,如果您不在同一个程序集中,则需要公开 exLog。

最后,这是 C#,风格规定类名应该是 PascalCased。养成良好的习惯。

【讨论】:

    【解决方案2】:

    我认为你想要类似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);
        }
    }
    

    【讨论】:

      【解决方案3】:

      我认为您对类、实例、构造函数和方法感到困惑。这不起作用:

      newMain.exLog("", "");
      

      因为在这种情况下exLog 是一个属性,而不是一个方法。 (这很令人困惑,因为您对类和属性使用相同的名称,这就是大多数约定不鼓励这样做的原因)。

      你可以在实例上调用一个方法

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

      但是您需要在 exLog 类中更改方法的名称(并添加返回类型),以免它们被解释为构造函数:

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

      【讨论】:

        【解决方案4】:
        class Main
        {
            public exLog exLog;
            public Main()
            {
                exLog = new exLog();
                exLog.ReadFileString("", "");
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-11
          • 1970-01-01
          相关资源
          最近更新 更多