Interface Question

rover2341

Is riding a roller coaster...Wee!
Reaction score
114
So I have a interface that a bunch of classes use. now that's all good but...
I am need of a function, that will return a list of instances, of those classes. (C#, .Net)
Example:

Code:
Interface MyInterface
bool Run() - Fuction
 
Class A : MyInterface
bool Run()
 
Class B : MyInterface
bool Run()
 
(These Work Fine)
 
 
 
Some Function:
List<Only Classes that use MyInterface > myList
myList.Add(New A());
myList.Add(New B());
return myList;
 
(Cant Figure out this line List<Only Classes that use MyInterface > myList)
 

rover2341

Is riding a roller coaster...Wee!
Reaction score
114
K sweet got me on the right track.. Ill update this post (of post again if someone else posts) once I have it solved, or If I cant get it to work.
 

seph ir oth

Mod'n Dat News Jon
Reaction score
262
You should simply make it a List<object>.

Code:
var myList = new List<object>();
myList.Add(New A());
myList.Add(New B());
return myList;

And then use something like this to later check all the objects in your list:

Code:
public static bool ImplementsInterface( this Type type, Type ifaceType ) {
        Type[] intf = type.GetInterfaces();
        for ( int i = 0; i < intf.Length; i++ ) {
            if ( intf[ i ] == ifaceType ) {
                return true;
            }
        }
        return false;
    }
 
if(ImplementsInterface(myList, Type.GetType("INTERFACE")) {
  //Do things
}

Alternatively, you could loop through the list and use Type.IsAssignableFrom.
 

rover2341

Is riding a roller coaster...Wee!
Reaction score
114
Well... That would not use my interface. But I plug interface where you had object. And BOOM. It works.

Thanks!

Code:
Interface Rule
Class MinX:Rule
Class MaxX:Rule
 
            List<Rule> buildRules = new List<Rule>();
            buildRules.Add(new MinX());
            buildRules.Add(new MaxX());

SOLVED
 

seph ir oth

Mod'n Dat News Jon
Reaction score
262
Well... That would not use my interface. But I plug interface where you had object. And BOOM. It works.

Thanks!

Code:
Interface Rule
Class MinX:Rule
Class MaxX:Rule
 
            List<Rule> buildRules = new List<Rule>();
            buildRules.Add(new MinX());
            buildRules.Add(new MaxX());

SOLVED

Ah yes, if you're using the newest version of C# you can do that (EDIT: perhaps 4.0+?).

My company is stuck in the stone ages :S
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top