vendredi 3 décembre 2021

How to cast object to interface with generic type [duplicate]

I want to cast an object instantiated from the Activator to a interface with a generic type.

public interface IFoo { }

public interface IBar<T> where T : IFoo {
   void Bal(T item);
}

public abstract class Bar<T> : IBar<T>
  where T : IFoo
{ 
  public abstract void Bal(T item);
}

public class Foo : IFoo
{ }

Now I have a lot of classes like Baz:

public class Baz : Bar<Foo>
{
  public override void Bal(Foo item);
}

I instantiale Baz with the activator.

var instanceOfBaz = Activator.CreateInstance(typeof(Baz));

Now I want to cast Baz back to the base implementation so I can call method Bal from the caller.

public IBar<IFoo> CreateInstanceOfBaz()
{
  var instanceOfBaz = Activator.CreateInstance(typeof(Baz));

  var castedBaz = (IBar<IFoo>) instanceOfBaz;
  var alsoCastedBaz = instanceOfBaz as IBar<IFoo>;

  return castedBaz;
}

But castedBaz will throw a InvalidCastException and alsoCastedBaz is null. So now I can't call the Bal method, nor get the object as IBar<IFoo>. I need this because I have a List of the IBar<IFoo> which I need in another place.

Above code will compile because the relations are valid, but runtime it will fail.

The project is running .NET Framework 4.7.2 and C# 7.

How do I solve my project so I can get the instantiated object as IBar<IFoo>? It is not an option to use reflection to call the Bal method, because I will still need the object in my list.





Aucun commentaire:

Enregistrer un commentaire