How to execute a Generic Interface method without knowing the exact type declaration

I have an interface declared as follows

public interface ILoadObjects<T> where T : class { List<T> LoadBySearch(); } 

Then I have a class declared as follows

 public class MyTestClass : ILoadObjects<MyTestClass> { List<MyTestClass> ILoadObjects<MyTestClass>.LoadBySearch() { List<MyTestClass> list = new List<MyTestClass>(); list.Add(new MyTestClass()); return list; } } 

Now what I would like to do is use this method defined in the interface for this class, not knowing what the class is.

 public void ExecuteTestClassMethod() { MyTestClass testObject = new MyTestClass(); object objectSource = testObject; object results = ((ILoadObjects<>)objectSource).LoadBySearch(); {... do something with results ...} } 

The above clearly does not work, so I would like to know how to do this in accordance with this.

thanks

+4
source share
1 answer

You must define a second non-generic interface, for example:

 public interface ILoadObjects<T> : ILoadObjects where T : class { List<T> LoadBySearch(); } public interface ILoadObjects { IList LoadBySearch(); } 

And declare your class as follows:

 public class MyTestClass : ILoadObjects<MyTestClass> { public List<MyTestClass> LoadBySearch() { List<MyTestClass> list = new List<MyTestClass>(); list.Add(new MyTestClass()); return list; } IList ILoadObjects.LoadBySearch() { return this.LoadBySearch(); } } 

The IEnumerable<T> and IEnumerable interfaces work the same way.

Now you can call the ILoadObjects.LoadBySearch method as follows:

 ((ILoadObjects)objectSource).LoadBySearch(); 
+5
source

All Articles