所以我有一張桌子,我可以在接近開發結束時保持我的移動應用程式的設定,我不禁認為他們這樣做是一種更簡潔的方式。
與其進行三個單獨的呼叫,我將如何進行一個呼叫來解釋回傳的不同資料型別。
我在 web api 專案中使用 ef core 6 和 c# 7。
public class SettingsService
{
TheAppDBContext db;
public SettingsService(TheAppDBContext dBContext)
{
db = dBContext;
}
public List<Settings> GetALLSettings()
{
return db.Settings.Where(w => w.IsActive == true &&
w.IsDeleted == false).ToList();
}
public bool? GetBoolSettingValueByKey(string Key)
{
return db.Settings.Where(w => w.IsActive == true && w.IsDeleted == false
&& w.Key.ToLower() == Key.ToLower()).First().BoolValue;
}
public string? GetStringSettingValueByKey(string Key)
{
return db.Settings.Where(w => w.IsActive == true && w.IsDeleted == false &&
w.Key.ToLower() == Key.ToLower()).First().StringValue;
}
public int? GetIntSettingValueByKey(string Key)
{
return db.Settings.Where(w => w.IsActive == true && w.IsDeleted == false &&
w.Key.ToLower() == Key.ToLower()).First().IntValue;
}
}
我的設定表如下,將來可能會在設定表中存盤日期和其他資料型別。

uj5u.com熱心網友回復:
如果您愿意失去一些型別安全,您可以使用使您的方法成為泛型方法并分析它的泛型型別引數:
public T GetSettingValueByKey<T>(string key)
{
var setting = db.Settings
.Where(w => w.IsActive == true && w.IsDeleted == false && w.Key.ToLower() == Key.ToLower())
.First();
var type = typeof(T);
if (type == typeof(bool))
{
return (T)(object)setting.BoolValue;
}
if (type == typeof(string))
{
return (T)(object)setting.StringValue;
}
if (type == typeof(int))
{
return (T)(object)setting.IntValue;
}
...
throw new InvalidOperationException();
}
這里的問題是沒有人限制用戶GetSettingValueByKey使用不受支持的型別進行呼叫,并且編譯器無法強制執行它(除非您想深入撰寫自定義代碼分析器)。
為了在沒有自定義分析器的情況下保持編譯時安全,您可以嘗試引入型別層次結構來表示可能的設定型別:
public interface ISettingValue{}
public interface ISettingValue<T> : ISettingValue
{
T Value { get; set; }
}
public struct IntSettingValue : ISettingValue<int?>
{
public int? Value { get; set; }
}
public struct BoolSettingValue : ISettingValue<bool?>
{
public bool? Value { get; set; }
}
...
public T GetSettingValueByKey<T>(string key) where T : ISettingValue
{
var setting = db.Settings
.Where(w => w.IsActive == true && w.IsDeleted == false && w.Key.ToLower() == Key.ToLower())
.First();
var type = typeof(T);
if (type == typeof(BoolSettingValue))
{
return (T)(object)new BoolSettingValue
{
Value = setting.BoolValue
};
}
if (type == typeof(int))
{
return (T)(object)new IntSettingValue
{
Value = setting.IntValue
};
}
...
throw new InvalidOperationException(); // write unit test with reflection to validate that this never happens
}
和用法:
SettingsService service = ...;
int? val = service.GetSettingValueByKey<IntSettingValue>("").Value;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/459623.html
上一篇:物體框架資料遷移
下一篇:僅在選中未選中的復選框時觸發事件
