簡體   English   中英

使用靜態類型成員以確保非靜態類中的類型安全

[英]Using static type member to ensure type-safety in a non-static class

我有一個這樣定義的靜態類:

public static class JobStatus
{ 
    public const string Completed = "Completed";
    public const string Failed = "Failed";
    public const string Stopped = "Stopped";
}

(這實際上是一個外部庫,因此無法更改)

在我的非靜態類中,我希望該類的成員確保您只能聲明該“類型”

public class JobOutput
{
    public string Output { get; set; }

    public string OutputError { get; set; }

    public JobStatus JobStatus { get; set; }
}

錯誤:“ JobStatus”:靜態類型不能用作返回類型/“ JobStatus”:靜態類型不能用作參數

是的,我知道您的眼睛在流血,但是我希望您明白了-我如何確保和實現JobStatus屬性的類型安全形式?

您不能,因為JobStatus所做的只是包含一些持有string的成員。 因此,您還必須將JobStatus屬性定義為字符串。

字符串沒有編譯時的安全性,它本來可以是枚舉。

你可以添加一個方法SetJobStatus(string status)到您的JobOutput類並進行JobStatus的二傳手私人。 然后在該方法中,檢查(使用反射) status字符串是否存在於靜態類JobStatus的公共const字段之一中。 或者,您可以在設置器中實現相同的功能。

請參見如何通過反射獲取類型的所有常量? 有關如何執行此操作的信息。 但這不是編譯時的安全,而是運行時。

您可以包裝JobStatus以使其“類型安全”,但看起來有些過頭了:

public sealed class JobStatusWrapper
{
     public static readonly JobStatusWrapper Completed 
         = new JobStatusWrapper(JobStatus.Completed);

     public static readonly JobStatusWrapper Failed
         = new JobStatusWrapper(JobStatus.Failed);

     public static readonly JobStatusWrapper Stopped
         = new JobStatusWrapper(JobStatus.Stopped);

     private readonly string description;
     private JobStatusWrapper(string description) {
         Debug.Assert(!string.IsNullOrEmpty(description));
         this.description = description; }

     public static implicit operator string(JobStatusWrapper status)
         => status.description;
}

現在您將使用它:

public class JobOutput
{
    //...
    public JobStatusWrapper JobStatus { get; set; }
}

而且,沒有辦法傳入或獲取沒有JobStatusWrapper中定義的基礎值之一的JobStatusnull除外)。 同樣,隱式運算符使包裝程序在JobStatus選項可用的任何地方都可用。

暫無
暫無

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

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