Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
I have some different objects that all of them have a integer field called Place. Is there a way to sort out this list without knowing what is the actual object? I mean just accessing
Place
您应该从基类派生您的类。
public class Base { public int Place; } public class Car : Base { // other properties } public class Human : Base { // other properties }
然后您可以创建一个基本类型列表,添加人和汽车。之后,您可以使用 LinqSort或OrderBy方法。
Sort
OrderBy
List<Base> list = new List<Base>(); list.Add(new Human { Place = 2 }); list.Add(new Car { Place = 1 }); var sortedList = list.Sort(x => x.Place);
不,因为object没有Place属性只有Car/Human做。
object
Car
Human
有几种方法可以解决这个问题:
引入一个基类
public class GameObject { public int Place { get; set; } } public class Car : GameObject {} public class Human : GameObject {} ... List<GameObject> GameObjects
使用通用接口
public interface IGameObject { int Place { get; } } public class Car : IGameObject { public int Place { get; set; } } public class Human : IGameObject { public int Place { get; set; } } List<IGameObject> GameObjects
最好的方法是使用接口。如果不能,您仍然可以使用dynamic关键字进行后期绑定:
dynamic
var list = new List<object> { new Car { Place = 3 }, new Human { Place = 1 }, new Car { Place = 2 } }; var sortedList = list.OrderBy(o => ((dynamic)o).Place);
您刚刚发现的是这些类型之间的关系。两者似乎都有 Place 属性,因此您应该提取一个接口 à Carla 。HumanIGameObject
IGameObject
您可以让他们实现一个接口IPlaceable并使用一个属性而不仅仅是一个字段:
IPlaceable
public interface IPlaceable { int Place { get; set; } } public class Car : IPlaceable { public int Place { get; set; } //Other related fields } public class Human : IPlaceable { public int Place { get; set; } //Other related fields } // Somwhere in program List<IPlaceable> GameObjects; // Somwhere else GameObjects.OrderBy(go => go.Place);
请注意,现在列表是 aList<IPlaceable>而不是 a List<Object>。
List<IPlaceable>
List<Object>
你能做的最好的就是使用一个接口,像这样:
public Interface IFoo { int place; }
并实现该接口:
public class Car : IFoo { public int Place; } public class Human : IFoo { public int Place; }
然后使用 linq:
List<IFoo> GameObjects; GameObjects.OrderBy(g => g.Place);
是的,它可以使用带反射的委托方法。据我所知,可能是其他一些巨头在不使用反射的情况下创建它