2011-06-24 7 views
0

特定のプロパティに対してそのアイテムを照会できるリストが必要です。そのプロパティが正しい値を持つ場合、そのアイテムを返します。汎用オブジェクト内からの値の取得

public class MyList<T> 
{ 
    public T[] items; 

    public Get(string name) 
    { 
     foreach(T item in items) 
     { 
      if(item.name == name) 
       return item; 
     } 
     return null; // if not found 
    } 
} 

タイプTは必ずしも私がチェックしているプロパティを持っていないので、上記のコンパイルエラーが発生します。それは理にかなっていますが、この行動を得るためには何が必要ですか?この質問の範囲外の理由で辞書を使用することはできませんが、辞書は私が再作成しようとしているものであることは事実です。

+1

オブジェクトに 'name'プロパティがないとどうなりますか? –

答えて

0

あなたは、このような性質を持っているタイプのものであるとTを制約する必要があります。

class Foo : INamed { 
    private readonly string name; 
    private readonly int foo; 
    public string Name { get { return this.name; } } 
    public Foo(string name, int foo) { 
     this.name = name; 
     this.foo = foo; 
    } 
} 

MyList<Foo> list = // some instance of MyList<Foo> 
Foo alice = list.Get("Alice"); 
3

あなたの関数定義の後ろに制約を入れて、例えば、

interface INamed { 
    string Name { get; } 
} 

public class MyList<T> where T : INamed 

    public T[] items; 

    public T Get(string name) { 
     foreach(T item in items) { 
     if(item.Name == name) 
      return item; 
     } 
     return null; // if not found 
    } 
} 

その後

public class MyList<T> where T : YourObjectThatHasNameProperty 
0

汎用制約を使用します。

public interface IHasName 
{ 
    string name; 
}  

public class MyList<T> where T : IHasName 
{ 
    public T[] items; 

    public Get(string name) 
    { 
     foreach(T item in items) 
     { 
      if(item.name == name) 
       return item; 
     } 
     return null; // if not found 
    } 
} 
1

あなたはTは、そのプロパティを持っているかどうかを確認するためにリフレクションを使用することもできます、関数の戻りnull場合:

public static Object TryGetPropertyValue(Object fromThis, String propertyName, Boolean isStatic) 
{ 
    // Get Type 
    Type baseType = fromThis.GetType(); 

    // Get additional binding flags 
    BindingFlags addFlag = BindingFlags.Instance; 
    if(isStatic) 
     addFlag = BindingFlags.Static; 

    // Get PropertyInfo 
    PropertyInfo info = baseType.GetProperty(propertyName, BindingFlags.Public | addFlag); 

    // Check if we found the Property and if we can read it 
    if(info == null || !info.CanRead) 
      return null; 

    // Return the value 
    return info.GetValue(fromThis, null); 
} 

編集:

Type type = item.GetType(); 
bool hasproperty = type.GetProperties().Where(p => p.Name.Equals("name")).Any(); 
+1

LINQなしでこれを行うことはできません: 'type.GetProperty(" name ")!= null'? – Bobby

2

次のようなリフレクションを使用することができますプロパティが提供されたオブジェクトに存在しないとみなすことができます。

関連する問題