I want to get specified type value from database. Here is my code:
public static T Get<T>(string key)
{
Databases.Context Context = new Databases.Context();
var i = Context.Setting.FirstOrDefault(_ => _.Key == key)?.Value;
if (i == null) {
return default;
}
switch (typeof(T))
{
case Type intType when intType == typeof(int):
{
if (int.TryParse(i, out int Result))
{
return Result;
}
else{
return default;
}
}
}
}
As the code above, part of my code is about to return int type value. However, VS reports an error that it cannot convert int to T. How can I solve this? Thank you.
>Solution :
To solve the error, you can use the Convert class to explicitly convert the int value to the desired type T.
public static T Get<T>(string key)
{
Databases.Context Context = new Databases.Context();
var i = Context.Setting.FirstOrDefault(_ => _.Key == key)?.Value;
if (i == null) {
return default;
}
switch (typeof(T))
{
case Type intType when intType == typeof(int):
{
if (int.TryParse(i, out int Result))
{
return (T)(object)Result;
}
else{
return default;
}
}
}
}
Alternatively, you can use the System.ComponentModel.TypeConverter class to perform the conversion. This approach allows you to handle more complex types and may be more flexible in some cases.
You can modify your code to use TypeConverter,
public static T Get<T>(string key)
{
Databases.Context Context = new Databases.Context();
var i = Context.Setting.FirstOrDefault(_ => _.Key == key)?.Value;
if (i == null) {
return default;
}
var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
if (converter.CanConvertFrom(typeof(string)))
{
return (T)converter.ConvertFromString(i);
}
else
{
return default;
}
}