lundi 8 juin 2015

Instantiate a class which implements a generic interface

I have an intercafe for specifying GetData method which returns one instance of the class by its ID

public interface ILabelData<T> {
  T GetData(object id);
}

and also have many different classes those who implements the interface and having members of course:

public class BTAC : ILabelData<BTAC> {
  // members...
  // and interface impl:
  public BTAC GetData(object id) {
    return null;
  }
}
public class KTAC : ILabelData<KTAC> {
  // members...
  // and interface impl:
  public KTAC GetData(object id) {
    return null;
  }
}

Within a calling method I would like to instantiate a BTAC/KTAC/... class and call their GetData method. (The purpose of it is becasue after I have the required instance I want to get its members and attributes. Getting the members and attributes is not part of my question.)

ILabelData<object> o = Activator.CreateInstance(type, new object[] { myID });
^^^^^^^^^^^^^^^^^^^^
object data = o.GetData(myID);

the problem is compiler error Cannot implicitly convert type 'object' to 'ILabelData< object >'

After instantiating the proper class of course I do need for the members and attributes, too, so it isn't enough to getting back ILabelData typed object.

How can I get a such kind of object? Some factory or whatever?





Aucun commentaire:

Enregistrer un commentaire