Conversão de tipo genérico universal de string
Minha tarefa é escrever um método StringToType () que converte uma string para o tipo especificado T.
Para tipos primitivos, eu uso o método Convert.ChangeType ()Para tipos de enum - Enum.TryParse ()Para todos os outros tipos personalizados, criei uma interface "IConvertibleFromString" que contém um método "FromString ()" para converter a cadeia no tipo especificado. Qualquer classe que precise converter de string deve implementar essa interface.Mas eu não gosto da maneira como eu implementei o método StringToType (). Eu gostaria de usar menos que a reflexão e garantir o máximo possível o desempenho.
Por favor, informe a melhor forma de implementá-lo / modificá-lo.
class Program
{
static bool StringToType<T>(string str, ref T value)
{
Type typeT = typeof(T);
bool isSuccess = false;
if (typeT.GetInterface("IConvertibleFromString") != null)
{
return (bool)typeT.GetMethod("FromString").Invoke(value, new object[] { str });
}
else if (typeT.IsEnum)
{
MethodInfo methodTryParse = typeT.GetMethod("TryParse").MakeGenericMethod(typeT);
return (bool)methodTryParse.Invoke(null, new object[] { str, value });
}
else if (typeT.IsPrimitive)
{
value = (T)Convert.ChangeType(str, typeT);
return true;
}
return isSuccess;
}
static void Main(string[] args)
{
string intStr = "23";
int val1 = 0;
bool res = StringToType<int>(intStr, ref val1);
Class1 c1;
res = StringToType<Class1>(intStr, ref c1);
Console.ReadKey();
}
}
interface IConvertibleFromString
{
bool FromString(string str);
}
class MySomeClass : IConvertibleFromString
{
int someVal;
public bool FromString(string str)
{
return int.TryParse(str, out someVal);
}
}