【问题标题】:Create Generic Method that accepts a List with custom object types and access similar properties创建接受具有自定义对象类型的列表并访问类似属性的通用方法
【发布时间】:2017-08-13 19:22:10
【问题描述】:

我正在创建一个搜索算法,该算法使用我创建的自定义对象搜索列表。它们共享相似的属性,但我似乎无法“隐式”访问这些属性..?一个例子:

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&lt;T&gt;(List&lt;T&gt; list, int indexOfList) where T: MyInterface

标签: c# search


【解决方案1】:

你可以为它创建接口:

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);
    }

T 类型中检索 int Id 并返回它:

    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));

【讨论】:

  • 太棒了,这正是我要找的东西。我很好奇。。我没有弄乱接口,但它们似乎等同于 C/C++ 中的头文件和声明功能等...?
  • @user3712563 不,interface 看起来不像 C++ 头文件。头文件在 C# 中看起来像 using。有关更多详细信息,您可以在 SO 中阅读:the first linkthe second link
猜你喜欢
  • 1970-01-01
  • 2016-12-11
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
相关资源
最近更新 更多