Reputation: 14682
I need a generic list with extended search mechanism, so i have created a generic list (base List<T>
) with an addirional indexer. So in this, if T is an object, then the list allows to fetch the item based on a field. Here is the Sample code
public class cStudent
{
public Int32 Age { get; set; }
public String Name { get; set; }
}
TestList<cStudent> l_objTestList = new TestList<cStudent>();
l_objTestList.Add(new cStudent { Age = 25, Name = "Pramodh" });
l_objTestList.Add(new cStudent { Age = 28, Name = "Sumodh" });
cStudent l_objDetails = l_objTestList["Name", "Pramodh"];
And my genereic list
class TestList<T> : List<T>
{
public T this[String p_strVariableName, String p_strVariableValue]
{
get
{
for (Int32 l_nIndex = 0; l_nIndex < this.Count; l_nIndex++)
{
PropertyInfo l_objPropertyInfo = (typeof(T)).GetProperty(p_strVariableName);
object l_obj = l_objPropertyInfo.GetValue("Name", null); // Wrong Statement -------> 1
}
return default(T);
}
}
}
But i can not get the value of the property, its throwing 'Target Exception'.
Please help me to resolve this.
Upvotes: 1
Views: 2990
Reputation: 6876
This line of code will need to be something like this...
object l_obj = l_objPropertyInfo.GetValue("Name", null);
=>
object l_obj = l_objPropertyInfo.GetValue(this[l_nIndex], null);
The first argument to the GetValue function is the object instance you want to retrieve the value of the property from.
Upvotes: 2