Como saber se Tipo A é implicitamente conversível para tipo B
-
19-09-2019 - |
Pergunta
Dada tipo A e tipo b, como posso, em tempo de execução, determinar se há uma conversão implícita de um para b?
Se isso não faz sentido, considere o seguinte método:
public PropertyInfo GetCompatibleProperty<T>(object instance, string propertyName)
{
var property = instance.GetType().GetProperty(propertyName);
bool isCompatibleProperty = !property.PropertyType.IsAssignableFrom(typeof(T));
if (!isCompatibleProperty) throw new Exception("OH NOES!!!");
return property;
}
E aqui está o código de chamada que eu quero trabalho:
// Since string.Length is an int property, and ints are convertible
// to double, this should work, but it doesn't. :-(
var property = GetCompatibleProperty<double>("someStringHere", "Length");
Solução
Note que IsAssignableFrom
não resolver o seu problema. Você tem que usar a reflexão como tal. Note-se a necessidade explícita de lidar com os tipos primitivos; estas listas são por §6.1.2 (conversões numéricas implícita) da especificação.
static class TypeExtensions {
static Dictionary<Type, List<Type>> dict = new Dictionary<Type, List<Type>>() {
{ typeof(decimal), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char) } },
{ typeof(double), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } },
{ typeof(float), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } },
{ typeof(ulong), new List<Type> { typeof(byte), typeof(ushort), typeof(uint), typeof(char) } },
{ typeof(long), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(char) } },
{ typeof(uint), new List<Type> { typeof(byte), typeof(ushort), typeof(char) } },
{ typeof(int), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(char) } },
{ typeof(ushort), new List<Type> { typeof(byte), typeof(char) } },
{ typeof(short), new List<Type> { typeof(byte) } }
};
public static bool IsCastableTo(this Type from, Type to) {
if (to.IsAssignableFrom(from)) {
return true;
}
if (dict.ContainsKey(to) && dict[to].Contains(from)) {
return true;
}
bool castable = from.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Any(
m => m.ReturnType == to &&
(m.Name == "op_Implicit" ||
m.Name == "op_Explicit")
);
return castable;
}
}
Uso:
bool b = typeof(A).IsCastableTo(typeof(B));
Outras dicas
As conversões implícitas que você precisa considerar:
- Identidade
- sbyte a curto, int, long, float, double, ou decimal
- byte para curto, ushort, int, uint, longo, ulong, float, double, ou decimal
- curta para int, long, float, double, ou decimal
- ushort para int, uint, longo, ulong, float, double, ou decimal
- int para long, float, double, ou decimal
- uint e longo, ulong, float, double, ou decimal
- tempo para flutuar, double, ou decimal
- ulong a flutuar, double, ou decimal
- char para ushort, int, uint, longo, ulong, float, double, ou decimal
- float para dobrar
- conversão de tipo Nullable
- Tipo de referência para objeto
- Derivado de classe para classe base
- Classe de interface implementada
- Interface a interface base
- matriz para matriz quando as matrizes têm o mesmo número de dimensões, há uma conversão implícita do tipo de elemento de fonte com o tipo de elemento de destino e o tipo de elemento de fonte e o tipo de elemento de destino são tipos de referência
- tipo Array para System.Array
- tipo Array para IList <> e suas interfaces de base
- tipo de delegado para System.Delegate
- conversão Boxing
- tipo Enum para System.Enum
- conversão definido pelo usuário (op_implicit)
Eu suponho que você está procurando para o último. Você precisa escrever algo parecido com um compilador para cobrir todos eles. Notável é que System.Linq.Expressions.Expression não tentou esta proeza.
A resposta aceita a esta pergunta lida com muitos casos, mas não todos. Por exemplo, aqui estão apenas algumas válidos casts / conversões que não são manipulados corretamente:
// explicit
var a = (byte)2;
var b = (decimal?)2M;
// implicit
double? c = (byte)2;
decimal? d = 4L;
A seguir, eu postei uma versão alternativa desta função que responde especificamente a questão de moldes implícita e conversões. Para mais detalhes, o conjunto de testes que eu usei para confirmá-lo, ea versão conversão explícita, confira meu post sobre o assunto .
public static bool IsImplicitlyCastableTo(this Type from, Type to)
{
// from http://www.codeducky.org/10-utilities-c-developers-should-know-part-one/
Throw.IfNull(from, "from");
Throw.IfNull(to, "to");
// not strictly necessary, but speeds things up
if (to.IsAssignableFrom(from))
{
return true;
}
try
{
// overload of GetMethod() from http://www.codeducky.org/10-utilities-c-developers-should-know-part-two/
// that takes Expression<Action>
ReflectionHelpers.GetMethod(() => AttemptImplicitCast<object, object>())
.GetGenericMethodDefinition()
.MakeGenericMethod(from, to)
.Invoke(null, new object[0]);
return true;
}
catch (TargetInvocationException ex)
{
return = !(
ex.InnerException is RuntimeBinderException
// if the code runs in an environment where this message is localized, we could attempt a known failure first and base the regex on it's message
&& Regex.IsMatch(ex.InnerException.Message, @"^The best overloaded method match for 'System.Collections.Generic.List<.*>.Add(.*)' has some invalid arguments$")
);
}
}
private static void AttemptImplicitCast<TFrom, TTo>()
{
// based on the IL produced by:
// dynamic list = new List<TTo>();
// list.Add(default(TFrom));
// We can't use the above code because it will mimic a cast in a generic method
// which doesn't have the same semantics as a cast in a non-generic method
var list = new List<TTo>(capacity: 1);
var binder = Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(
flags: CSharpBinderFlags.ResultDiscarded,
name: "Add",
typeArguments: null,
context: typeof(TypeHelpers), // the current type
argumentInfo: new[]
{
CSharpArgumentInfo.Create(flags: CSharpArgumentInfoFlags.None, name: null),
CSharpArgumentInfo.Create(
flags: CSharpArgumentInfoFlags.UseCompileTimeType,
name: null
),
}
);
var callSite = CallSite<Action<CallSite, object, TFrom>>.Create(binder);
callSite.Target.Invoke(callSite, list, default(TFrom));
}