Generics: casting and value types, why is this illegal?

后端 未结 3 803
太阳男子
太阳男子 2020-11-29 09:46

Why is this a compile time error?

public TCastTo CastMe(TSource i)
{
     return (TCastTo)i;
}

Error:

3条回答
  •  旧巷少年郎
    2020-11-29 09:58

    The compile error is caused because TSource cannot be implicitly cast to TCastTo. The two types may share a branch on their inheritance tree, but there is no guarantee. If you wanted to call only types that did share an ancestor, you should modify the CastMe() signature to use the ancestor type instead of generics.

    The runtime error example avoids the error in your first example by first casting the TSource i to an object, something all objects in C# derive from. While the compiler doesn't complain (because object -> something that derives from it, could be valid), the behaviour of casting via (Type)variable syntax will throw if the cast is invalid. (The same problem that the compiler prevented from happening in example 1).

    Another solution, which does something similar to what you're looking for...

        public static T2 CastTo(T input, Func convert)
        {
            return convert(input);
        }
    

    You'd call it like this.

    int a = 314;
    long b = CastTo(a, i=>(long)i);
    

    Hopefully this helps.

提交回复
热议问题