2017-08-13 12 views
0

私が作成したカスタムオブジェクトでリストを検索する検索アルゴリズムを作成しています。彼らは同様のプロパティを共有しますが、これらのプロパティに "暗黙的に"アクセスすることはできません。例:カスタムオブジェクトタイプのリストを受け入れて同様のプロパティにアクセスする汎用メソッドを作成

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 
} 

これは可能ですか?私はこれをする必要があるものに変更するために何が必要ですか?

ありがとうございます。

+0

あなたのクラスの両方を実装する共通のインタフェースを作成します。次に、あなたのメソッドにジェネリック制約を簡単に追加することができます。例えば、 'int _GetIDFromList (List list、int indexOfList)ここでT:MyInterface' – HimBromBeere

答えて

4

あなたはそれのためのインタフェースを作成することができます:

public interface IId 
{ 
    int ID { get; set; } 
} 

public class Exit : IId 
{ 
    int ID { get; set; } 
} 

public class Room : IId 
{ 
    int ID { get; set; } 
} 

private int _GetIDFromList<T>(List<T> list, int indexOfList) where T : IId 
{ 
    return list[indexOfList].ID; 
} 

それともあなたはそれのためにReflectionExpressionを使用することができます。

public static Expression<Func<T, P>> GetGetter<T, P>(string propName) 
    { 
     var parameter = Expression.Parameter(typeof(T)); 
     var property = Expression.PropertyOrField(parameter, propName); 
     return Expression.Lambda<Func<T, P>>(property, parameter); 
    } 

RetrivesがタイプTからIdをint型と、それを返します。

private static int _GetIDFromList<T>(List<T> list, int indexOfList) 
    { 
     var lambda = GetGetter<T, int>("Id").Compile(); 
     return lambda(list[indexOfList]); 
    } 

私は少しrewrですお部屋のクラスをOTE:

public class Room 
    { 
     public int ID { get; set; } 
    } 

と使用方法:

Console.WriteLine(_GetIDFromList(new List<Room> { new Room { ID = 5 } }, 0)); 
+0

これはまさに私が探しているものです。 atのInterfacesを使いこなしましたが、C/C++のヘッダファイルや関数の宣言などのように見えますか? – user3712563

+0

@ user3712563いいえ、 'interface'はヘッダファイルC++のようではありません。ヘッダーファイルはC#で 'using 'のように見えます。詳細については、SO:[最初のリンク](https://stackoverflow.com/questions/6744105/are-c-header-h-files-like-interfaces-in-c-java)を参照してください。と[第2のリンク](https://stackoverflow.com/questions/22697454/interfaces-and-headers) –

関連する問題