Skip to content

Instantly share code, notes, and snippets.

@hazzik
Created May 28, 2011 17:51
Show Gist options
  • Save hazzik/997069 to your computer and use it in GitHub Desktop.
Save hazzik/997069 to your computer and use it in GitHub Desktop.
bool CanConvert(Type source, Type destination)
{
try
{
Expression.Convert(Expression.Default(source), destination);
return true;
}
catch (InvalidOperationException)
{
return false;
}
}
@AlexMAS
Copy link

AlexMAS commented May 28, 2011

Такое поведение нормально?

class Program
{
    private static void Main()
    {
        // .NET 4.0
        Console.WriteLine(CanCast(typeof(A), typeof(B))); // true
        Console.WriteLine(CanCast(typeof(B), typeof(A))); // true
        Console.WriteLine(CanCast(typeof(int), typeof(long))); // true
        Console.WriteLine(CanCast(typeof(long), typeof(int))); // true
        Console.ReadKey();
    }

    public class A
    {
    }

    public class B : A
    {
    }

    private static bool CanCast(Type s, Type d)
    {
        try
        {
            Expression.Convert(Expression.Default(s), d);
            return true;
        }
        catch (InvalidOperationException)
        {
            return false;
        }
    }
}

@hazzik
Copy link
Author

hazzik commented May 28, 2011 via email

@AlexMAS
Copy link

AlexMAS commented May 28, 2011

Согласен, задача не тривиальная. Если это решение задачу решает, почему бы и нет ;)

@AlexMAS
Copy link

AlexMAS commented May 30, 2011

bool CanCast(Type s, Type d)
{
    if (!d.IsAssignableFrom(s) && s.IsAssignableFrom(d))
    {
        return false;
    }

    try
    {
        Expression.Convert(Expression.Default(s), d);
        return true;
    }
    catch (InvalidOperationException)
    {
        return false;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment