I have 3 projects: 2 are class libraries and 1 is console app:
-
class library "AnimalManagers". In AnimalManagers is
public interface AnimalAgressiveBase{ string Bark<TAnimal>(TAnimal animal); } public abstract class AnimalAgressive<TEnemy> : AnimalAggresiveBase { public abstract string BarkAtEnemy(TEnemy enemy); public string Bark<TAnimal>(TAnimal animal){ return BarkAtEnemy((TEnemy)animal);// <---- Invalid cast exception even if type of object "animal" is Cat and we call this method from Dog class } } public class AnimalManager { public void WatchAnimal<TAnimalModel> (TAnimalModel animalModel) { //<-- in example, animalModel is Cat("lucy") var aggresiveAnimalDog = GetAgresiveAnimal(); //<-- returns object from dynamically loaded class Dog so this is basicaly new Dog() if animal models library class were referenced if(aggresiveAnimalData != null) aggresiveAnimalDog .Bark(animalModel); } public AnimalAgressiveBase GetAgresiveAnimal(){ Assembly.LoadFrom("..\\AnimalModels.dll"); .... return aggresiveAnimal; //In This case Dog because he implements correct interface } }
-
class library "AnimalModels" In AnimalModels are model classes Cat and Dog
public class Cat { public string Name {get;set;} } public class Dog : AnimalAgressive<Cat> { public override string BarkAtEnemy(Cat enemy){return enemy.Name;} }
Both libraries are referenced in ConsoleApp "Zoo" , and I get invalid type exception when I call
var manager = new AnimalManager();
var manager.WatchAnimal(new Cat{Name="lucy"});
I got invalid cast exception because of dynamically loaded assembly types doesnt coresspond with referenced types, even if they got same AssemblyQualifiedName.
Any solutions? Goal is to load assembly get types that implements known interface (ex: AnimalAggressiveBase) and call method that I pass data of some type.
Aucun commentaire:
Enregistrer un commentaire