Interface Question

Discussion in 'General Programming Support' started by rover2341, Feb 3, 2014.

  1. rover2341

    rover2341 Is riding a roller coaster...Wee!

    Ratings:
    +114 / 0 / -0
    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)
    
     
  2. Accname

    Accname 2D-Graphics enthusiast

    Ratings:
    +1,551 / 4 / -4
    • Like Like x 1
  3. rover2341

    rover2341 Is riding a roller coaster...Wee!

    Ratings:
    +114 / 0 / -0
    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.
     
  4. seph ir oth

    seph ir oth Mod'n Dat News Jon Staff Member

    Ratings:
    +261 / 2 / -0
    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.
     
    • Like Like x 1
  5. rover2341

    rover2341 Is riding a roller coaster...Wee!

    Ratings:
    +114 / 0 / -0
    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
     
  6. seph ir oth

    seph ir oth Mod'n Dat News Jon Staff Member

    Ratings:
    +261 / 2 / -0
    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
     
  7. rover2341

    rover2341 Is riding a roller coaster...Wee!

    Ratings:
    +114 / 0 / -0
    4.5
     
    • Like Like x 1

Share This Page