我正在创建一个搜索算法,该搜索算法使用我创建的自定义对象搜索列表。他们有相似的属性,但我似乎无法隐含地"访问这些属性..?一个例子:
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 :(得分: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;
}
或者您可以使用Reflection
和Expression
:
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);
}
从类型Id
中重新转换int T
并返回它:
private static int _GetIDFromList<T>(List<T> list, int indexOfList)
{
var lambda = GetGetter<T, int>("Id").Compile();
return lambda(list[indexOfList]);
}
我很少改写你的Room课程:
public class Room
{
public int ID { get; set; }
}
用法:
Console.WriteLine(_GetIDFromList(new List<Room> { new Room { ID = 5 } }, 0));