Unable to pass object of type "MyType" for input "IMyInterface`1 [System.IConvertible]"

I had a problem casting my implementation classes into my common interface. I have several inner classes inside a class that implement this interface. Then I have a method that should return any of these classes, but casting to it fails for T! = String.

Example:

public interface IMyInterface<out T> where T : IConvertible
{/*Contents*/}

internal class MyStringClass : IMyInterface<String>  {/*Contents*/}
internal class MySingleClass : IMyInterface<Single>  {/*Contents*/}

IMyInterface<IConvertible> CreateMyObject(Type type)
{
    return (IMyInterface<IConvertible>)Activator.CreateInstance(type);
}

Seeing that String is a reference type and the rest are structures, is this related? There must be something missing here. (Perhaps also related: if I remove the covariance T, casting MyStringClass also stops.)

I usually don't work with C #, so this is a bit unfamiliar to me. Any explanation why this does not work, as well as any pointer to a solution, is welcome.

EDIT: , IMyInterface, type (typeof)

EDIT2: , T covariant , , , T = String , T = ValueType. , , ...

+4
1

out, T, , MSDN out:

, .

UPDATE: ( , ), :

public interface IMyInterface
{ /*non-generic content*/}

public interface IMyInterface<out T> : IMyInterface where T : IConvertible
{/*Contents*/}

internal class MyStringClass : IMyInterface<String> {/*Contents*/}
internal class MySingleClass : IMyInterface<Single> {/*Contents*/}

static IMyInterface CreateMyObject(Type type)
{
    return (IMyInterface)Activator.CreateInstance(type);
}
+5

Source: https://habr.com/ru/post/1548462/


All Articles