var cats = catsource.Select(c => new
{
CatId = c.catId,
Name = c.Name,
}).ToList();
var myCatObject = new CatData(cats);
這不起作用,因爲編譯器說,它不能轉換成cats
List<T>
。
cats
是一個匿名類型,CatData
是:
public class CatData<T>
{
public int total;
public int records;
public List<T> records;
public CatData(List<T> dataObjects, int totalRecords, int numberOfRows)
{
total = (int)Math.Ceiling((double)totalRecords/numberOfRows);
records = totalRecords;
rows = dataObjects;
}
}
任何想法?
編輯:
所以我做了這個代碼,但仍有一個問題:
public class CatData
{
public int total;
public int records;
public List<T> rows;
private CatData(List<T> dataObjects, int totalRecords, int numberOfRows)
{
total = (int)Math.Ceiling((double)totalRecords/numberOfRows);
records = totalRecords;
rows = dataObjects;
}
public static CatData<T> Create(List<T> dataObjects, int totalRecords, int numberOfRows)
{
return new CatData<T>(dataObjects, totalRecords, numberOfRows);
}
}
此代碼對的<T>
每個實例的錯誤說
無法解析符號T
如果我改變類是public class CatData<T>
它編譯,但我不能有這樣的代碼:因爲它說
的類型參數的數目不正確
CatData.Create(records, totalRecords, rows);
。
更新來解釋我想要什麼:
我想創建具有匿名類型對象的列表
var someList = someCollection.Select(new { ... });
我想創建一個對象,它存儲他們作爲List<anonymous>
var myObject = new myObject(someList, 5);
所以我可以做:
myObject.someValue; // 5 (stored it in the constructor)
myObject.myList.Count(); // can count how many anonymous objects are in there
也許我應該只是將其存儲爲List<object>
。
我真的不明白,也許我只是有點太厚。我剛剛結束了這個:
public CatData(List<object> dataObjects, int totalRecords, int numberOfRows)
作爲我的構造函數。
var catData = new CatData(records.Cast<object>().ToList(), totalRecords, rows);
什麼是'CatData'發佈其定義 –
什麼是'T'在CatData構造? –
從什麼時候構造函數允許泛型參數? – Crono