2015-05-08 57 views
0

嘿,我有兩個類C#主類包括「繼承」

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

    } 
} 

class exLog 
{ 
    public exLog() 
    { 

    } 
    public exLog(String where) 
    { 

    } 
    public exLog(String where, String message) 
    { 

    } 
} 

我試着撥打艾克斯勞格直接不給艾克斯勞格的參數。所以我可以用Main Method調用任何類。 我該怎麼做?

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

我喜歡叫他們像在主

+0

閱讀關於類和[構造](https://msdn.microsoft.com/en-us/library/ace5hbzh.aspx)。第一類中的「Main」是構造函數,所以其他類中的其他*方法*。 – Habib

+0

'公共exLog exLog = new exLog();'附註 - 類名應該以大寫字母(和小寫字母的字段)開頭 - 這是相當普遍的約定。 –

+0

@DStanley在C#中相當普遍:)。 –

回答

0

依我看你想要的東西像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); 
    } 
} 
+0

非常感謝你你是我今日的英雄:D –

1

一個funtion你可以只要你初始化它調用它。

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

此外,如果您不在同一個程序集中,則需要公開exLog。

最後,這是C#,風格決定類名應該是PascalCased。這是一個很好的習慣。

0

我覺得你對類,實例,構造函數和方法感到困惑。這不起作用:

newMain.exLog("", ""); 

因爲exLog在這種情況下是財產,不是方法。 (這很令人困惑,因爲你爲類和屬性使用了相同的名稱,這就是爲什麼大多數約定都不鼓勵這樣做的原因)。

你可以調用一個方法實例

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

但隨後你需要改變的方法的名稱(並添加返回類型)在exLog類,以便他們沒有得到解釋爲構造函數:

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