简体   繁体   English

创建与类属性相同类型的List

[英]Create a List with the same type that a class property

I want to create a list taking all the values that a property has in a list of certain class and add these values into another list whose type is the same than the class property. 我想创建一个列表,获取属性在某个类列表中的所有值,并将这些值添加到另一个类型与类属性相同的列表中。

Lets suppose I have the Book class: 让我们假设我有Book类:

public class Book{
    public int code;
    public string genre;
    public string author;
    public string synopsis;
}

Then, I have some method with a List<Book> myList containing some books and I want to populate a list of bookCodes which should be of the same type than Book's property code. 然后,我有一个方法, List<Book> myList包含一些书籍,我想填充一个bookCodes列表,它应该与Book的属性代码类型相同。 I want not to change the declaration of the list of BookCodes List<int> myBookCodes if some day the code property is changed from int to long or Guid , for example. 我想不要更改BookCodes List<int> myBookCodes列表的声明,如果有一天code属性从int更改为longGuid ,例如。

I have tried things such as 我尝试过诸如此类的东西

var myBookCodes = new List<typeof(Books.code)>

But I get a "Type expected" error. 但我收到“预期类型”错误。

I have also tried to use reflection but I also got errors: 我也试过使用反射,但我也有错误:

System.Reflection.PropertyInfo bookCodeProperty = typeof(Book).GetProperty("code");
Type bookCodeType = bookCodeProperty.PropertyType;

var myBookCodes = new List <>(bookCodeType)

But in this case the compiler complains "bookCodeType is a variable but it is used like a type". 但在这种情况下,编译器会抱怨“bookCodeType是一个变量,但它像一个类型一样使用”。

Is there a way to do this? 有没有办法做到这一点?

This is easy... you just project the list and the type is taken care of for you: 这很容易......您只需预测列表并为您处理类型:

List<Book> myList ...
var codesList = myList.Select(b => b.code).ToList();

if some day the code property is changed from int to long or Guid 如果有一天代码属性从int更改为long或Guid

Then the code still works, and is now the new type. 然后代码仍然有效,现在是新类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM