[英]C# EmptyIfNull extension for any IEnumerable to return empty derived type
[英]Is there a way to make a IEnumerable method that lets me return any list type in c#?
所以目前,你可以想象我有 1 個方法,它是函數喜歡的構造函數
info.PersonalInfo=getPersonalInfo(Id);
info.MedicalInfo=getMedicalInfo(Id);
問題是,所有這些獲取數據和獲取二進制文件都在重復 95% 的代碼
using (CVDataEntities data = new CVDataEntities())
{
var temp = data.PersonalInfo.Where(m => m.Id == Id).FirstOrDefault();
return temp;
}
唯一改變的不是 PersonalInfo 而是它的 MedicalInfo。 我想使用一個開關,只發送一個數字作為我想要的特定 object 的選擇器。
但問題是方法是這樣的,它只能返回
public IEnumerable<PersonalInfo> getPersonalInfo (string Id)
有什么方法可以讓我返回任何 object 的 IEnumerable,或者有沒有更好的方法來 go 解決這個問題。 我想這樣做主要是為了將代碼從 400 行減少到最多 200 行。
嘗試使用泛型方法,您將能夠在調用時指定 function 的返回類型。 這可能會使您的代碼如下所示:
public IEnumerable<T> getInfo<T>(string id)
{
// Some code
}
// Calling the function
info.PersonalInfo = getInfo<PersonalInfo>(Id);
info.MedicalInfo = getInfo<MedicalInfo>(Id);
但是使用它時要小心,因為編譯器不知道T
是什么類型(它只在運行時定義),所以在處理數據時可能會導致一些錯誤(比如缺少特定類型獨有的屬性/方法)
編輯:Johnathan Barclay 通過評論// some code
bit 是相關的並詢問“如何在data
上選擇正確的屬性?如何訪問T
上的Id
屬性”提出了一個很好的觀點。
要獲取正確的屬性並訪問Id
屬性,您可以使用System.Reflection並添加一個字符串參數來獲取您要使用的屬性的名稱,另一個將Id
屬性名稱提供給 function:
public IEnumerable<T> getInfo<T>(string id, string propertyToReadName, string propertyToCompareName)
{
using (CVDataEntities data = new CVDataEntities())
{
// Getting the enumerable not filtered first
IEnumerable<T> unfilteredList = (IEnumerable<T>)data.GetType() // Get the type
.GetProperty(propertyToReadName, typeof(T)) // Get the property (PersonalInfo or MedicalInfo)
.GetValue(data); // Get the value of this property in the `data` instance
// Filtering the list
IEnumerable<T> filteredList = unfilteredList.Where(m =>
typeof(T).GetProperty(propertyToCompareName) // Get the "id" property using parameter
.GetValue(m) // Get the "id" value of m instance
.Equals(id)); // Check if it equals the id given as parameter
return filteredList;
}
}
// Calling the function
info.PersonalInfo = getInfo<PersonalInfo>(Id, "PersonalInfo", "Id");
info.MedicalInfo = getInfo<MedicalInfo>(Id, "MedicalInfo", "Id");
如果要返回單個元素而不是IEnumerable
,請不要忘記將 function 的返回類型從IEnumerable<T>
更改為T
並在返回行添加.FirstOrDefault()
請注意,您還可以為參數propertyToCompareName
提供另一個值,並與T
class 的另一個屬性進行比較
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.