私が作成したカスタムオブジェクトでリストを検索する検索アルゴリズムを作成しています。彼らは同様のプロパティを共有しますが、これらのプロパティに "暗黙的に"アクセスすることはできません。例:カスタムオブジェクトタイプのリストを受け入れて同様のプロパティにアクセスする汎用メソッドを作成
public class Exit{
int ID {get;set;}
}
public class Room{
int ID {get;set;}
}
static void Main(string[] args){
List<Exit> exits = new List<Exit>();
List<Room> rooms = new List<Room>();
// added numerous instances of objects to both lists
int getExitID = _GetIDFromList(exits, 2); //example
int getRoomID = _GetIDFromList(rooms, 7); //example
}
private int _GetIDFromList<T>(List<T> list, int indexOfList){
return list[indexOfList].ID; // this gives me error it can't find ID
}
これは可能ですか?私はこれをする必要があるものに変更するために何が必要ですか?
ありがとうございます。
あなたのクラスの両方を実装する共通のインタフェースを作成します。次に、あなたのメソッドにジェネリック制約を簡単に追加することができます。例えば、 'int _GetIDFromList(List list、int indexOfList)ここでT:MyInterface' –
HimBromBeere