How do you 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();
}
I then 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'd like to do, is use that method defined in the interface against that class without having to know 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 obviously doesnt work, so I'd like to know ho开发者_StackOverflow中文版w to do something along the lines of that.
Thanks
You will have do define a second non-generic interface like this:
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 like this:
((ILoadObjects)objectSource).LoadBySearch();
精彩评论