簡體   English   中英

C#靜態類和數據成員問題

[英]C# static class and data members question

我不確定如何使用C#.Net 3.5實現我的想法。 我有一個稱為Common的靜態類,其中包含通用方法。 方法之一是PrepareReportParameters。 此方法接受字符串ReportParams並將其解析以獲取參數值。 我將此ReportParams字符串加載到Dictionary中。 然后驗證是否存在必需的元素。 我檢查像:

if (ReportParamList.ContainsKey("PAccount"))
{
    ReportParamList.TryGetValue("PAccount", out PrimaryAccount);
}

其中PrimaryAccount是我的Common類中的靜態變量。 我可以在其他地方以Common.PrimaryAccount的身份訪問它。

雖然,這種訪問報表參數的方法將起作用,但我希望將PrimaryAccount作為Common.ReportParameters.PrimaryAccount進行訪問。 這是問題所在,我不知道ReportParameters應該是哪種類型,如何將所有報告參數添加到該類型? 我應該如何定義ReportParameters? 聽起來可行還是沒有任何意義。 請幫忙!

聽起來您基本上已經習慣了使用全局變量來傳遞狀態。 通常這是一個非常糟糕的主意。

為什么您的方法不只返回主要帳戶值? 然后可以將其傳遞給其他需要它的東西。

如果您發現自己有很多靜態成員-特別是如果其他類正在獲取可變的靜態變量-請考慮是否可以應用更多的OO設計。 它會更容易理解,更容易測試和更易於維護。

編輯:好的,所以目前您有:

public static class Common
{
    public static int PrimaryAccount;
    // other static fields

    public static void PrepareReportParameters(string reportParameters)
    {
        // Code to set the fields
    }
}

而是使用普通的類:

public class ReportParameters
{
    public int PrimaryAccount { get; private set; }
    // Other properties

    private ReportParameters(int primaryAccount, ....)
    {
        this.PrimaryAccount = primaryAccount;
    }

    // Could use a constructor instead, but I prefer methods when they're going to
    // do work
    public static ReportParameters Parse(string report)
    {
        // Parse the parameter, save values into local variables, then
        return new ReportParameters(primaryAccount, ...);
    }
}

然后從其余代碼中調用此方法,並將ReportParameters引用傳遞給需要它的任何對象。

您可以使用相關的強類型屬性創建一個名為ReportParameters的類,並為Common提供它的靜態實例嗎?

我不確定這是最好的設計。 僅在調用PrepareReportParameters后才允許訪問Common.PrimaryAccount,這有一定程度的“代碼異味”。 也許您會考慮在構造函數中傳入參數的實例類?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM