IsAssignableFrom does not always give a definitive answer. What are the alternatives?

Possible duplicate:
How to determine if type A is implicitly converted to type B

When you speak

int i = 1;
double d = i;

the compiler has no problem with this.

However, when I ask

typeof(double).IsAssignableFrom(typeof(int))

the answer is false. The conversion from intto doubleis supposedly through an implicit operator.

Now consider a situation where I do not know 2 types in advance. I don’t even know if they are structor classes. Is there a way to figure out that one type can be passed to another without trying to catch an InvalidCastException?

+5
source share
3 answers

IsAssignableFrom , , . is, , .

msdn sez IsAssignableFrom : "true, c , c, , c , c c. false, , c - Nothing."

http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx

, , , , , IsAssignableFrom.

, - invalidcastexception , , , , .

+5

int double:

double Func<T>(T t)
{
     // return (double)t; -- won't compile
     return (double)(object)t; // `InvalidCastException` if T = int
}

:

int i = 1;
double d = (double)i;

, . , .

, ?

  • ? , int double.
  • ? , int double
  • ? , double int
  • -? Ok, int double System.Object ( ), IConvertable, (. ),
+6

, , , , (, ).

IsAssignableFrom , System.Reflection, (. 1191). ( ) , , , mscorlib.

[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool CanCastTo(IntPtr target);

as , .

If you have good reason for this, it can be beneficial (and faster) to catch an exception and create a cache type of types as they are evaluated. I would definitely be interested in a better solution.

+1
source

All Articles