[英]Get enum values from web.config at run time
我有一個枚舉,我想在運行時從 web.config 獲取它。 我開始閱讀有關構建提供程序的信息,但這似乎適用於類。 有人可以給我指出一個例子,或者至少指出我正確的方向。
現在我在 web.config 中有一個逗號分隔的值列表,這不是類型安全的並且容易出錯。
如果有另一種方法可以獲得這種類型的“動態枚舉”,我願意接受其他想法。
謝謝!
您可以使用ConfigurationManager並將值轉換為枚舉:
<configuration>
<appSettings>
<add key="YourEnum" value="BlueSky" />
</appSettings>
</configuration>
string configValue = ConfigurationManager.AppSettings["YourEnum"];
YourEnumType value = (YourEnumType)Enum.Parse(typeof(YourEnumType), configValue);
Microsoft.Extensions.Configuration
將反序列化存儲在 JSON 字符串中的枚舉,我發現這是解決這個問題的好方法。
舉個例子:
public enum Format
{
UNKNOWN = 0,
PNG,
JPEG
}
public class ImageOptions
{
/* List of supported file types */
public List<Format> SupportedFileTypes { get; set; }
}
/* Options config dict */
public static Dictionary<string, string> DefaultImageServiceConfigDict = new Dictionary<string, string>
{
/* Image Options NOTE: Enums stored as strings!! */
{"ImageServiceOptions:SupportedFileTypes:0", "png"},
{"ImageServiceOptions:SupportedFileTypes:1", "jpeg"},
};
/* Read options */
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(DefaultImageServiceConfigDict);
configuration = builder.Build();
/* Parses config, including enum deserialisation by name */
imageConfig = config.GetSection(nameof(ImageOptions)).TryGet<ImageServiceOptions();
如果我是你,那么我會設計我自己的 Enum 類。 這樣您就可以將其序列化為 XML 或在運行時構建它。 它還將確保您仍然具有類型安全性。
通常,數據將存儲在類中的字典類型或鍵/值對列表中。 然后你可以在配置文件中存儲一個值列表(看看如何讀取列表數據)
看看這里以獲得一些想法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.