2016-06-13 62 views
-1

只有第二個問題在這裏提出,所以如果我遺漏了一些代碼可能會幫助您評論這麼說。C#如何在方法運行之前使用派生類變量設置基類變量

我有一個抽象類Report,派生類叫做BusinessBreakdown,派生類叫做BusinessWrittenBreakdown。

如何更改此代碼,使BusinessWrittenBreakdown中的ReportTitle,DateField和DataLabel在BuildDefinition方法運行之前在BusinessBreakdown中設置具有相同名稱的構造函數。

我試過使用谷歌搜索和所有,但不能解決如何,這是我得到。出現的錯誤似乎沒有幫助,所以我更多地尋求一種可行的不同方法。

public class BusinessBreakdown : Report 
{ 
    static string ReportTitle; 
    static string DateField; 
    static string DateLabel; 

    public BusinessBreakdown(string theReportTitle, string theDateField, string theDateLabel) 
     : base(BuildDefinition) 
    { 
     ReportTitle = theReportTitle; 
     DateField = theDateField; 
     DateLabel = theDateLabel; 
    } 

    /// <summary> 
    /// Build the report definition 
    /// </summary> 
    /// <returns></returns> 
    public static ReportDef BuildDefinition(Settings settings) 
    { 

     // Create definition 
     var rdef = new ReportDef(); 

     // Create configuration context 
     var context = new FsConfigContext(); 
     rdef.ConfigContext = context; 

     // Report title 
     rdef.ReportTitle = ReportTitle; 

     // Create report date range configuration 
     ConfigDateRange drange = new ConfigDateRange(settings, "ReportDate", Config.ConfigDisposition.Filter, 
             new FilterExpressionDef 
             { 
              Expression = DateField 
             }, DateLabel); 

     rdef.ReportDate = drange; 

///// code ... 

     return rdef; 
    } 
} 
} 


public class BusinessWrittenBreakdown : BusinessBreakdown 
{ 
    // Report title 
    static string ReportTitle = "Business Written Breakdown Report"; 
    // Report date range and label 
    static string DateField = "COMMISS.BRDateWritten"; 
    static string DateLabel = "Written Date"; 

    public BusinessWrittenBreakdown() 
     : base(ReportTitle, DateField, DateLabel) 
    { 
    }   
/// more code... 
    } 
} 
+5

你的領域爲什麼是靜態的? – sstan

+5

你說你得到一個錯誤,但不要說什麼,或者它在哪裏。 –

+3

它不清楚你在問什麼。你能舉一個你想要發生什麼的例子嗎? –

回答

0

你完全無法控制該序列。這是一個static方法。

public static ReportDef BuildDefinition(Settings settings) 

根據定義,有人可能會叫不不斷這個方法調用任何類的構造函數。因此,它無法讓他們首先調用構造函數。

靜態屬性和方法在類的所有實例之間共享。你有一個具有這些不同屬性的構造函數表明你想爲一個報表創建一個類的實例,然後爲另一個報表創建另一個具有不同參數的實例。

在這種情況下,它看起來並不像你需要靜態方法,而只是增加了複雜性。所以我會刪除static。這意味着每個屬性或字段都是「實例」屬性或字段。它屬於類的每個單獨實例,而不是在類的實例之間共享。

+0

謝謝,這是有道理的,自大學以來,我一年沒有編寫很多程序,並忘記了一些簡單的東西。 其餘的代碼是否可以在沒有靜態方法的情況下工作,還是需要改變我獲取變量的方式? –

相關問題