2012-06-25 64 views
2

我努力讓我的頭圍繞如何做到以下幾點:通用方法綁定到對象

我有幾個方法,返回不同的強類型的IEnumerable對象。 這些強類型的類共享公共基類,該基類公開了我想要在Linq選擇器中訪問的屬性。

但是,我似乎無法得到這個工作。如果我只是在方法中傳遞基類型,那麼綁定IEnumerable時會出錯,因爲派生類中可用的屬性不可用。

如果我嘗試傳遞類型,那麼因爲Linq表達式不知道類型,我不能訪問我在我的Linq表達式中需要的屬性。

我需要以某種方式告訴Linq表達式,我的IEnumerable類型是從我的基類派生的。 下面是什麼,我試圖做一個例子:

private IEnumerable<MyStronglyTypedResultSet> GetReportDetails() 
{ 
    // this returns the IEnumerable of the derived type 
} 

public class MyBaseClass 
{ 
    public Guid UserId {get; set;} 
    public string OfficeName {get; set;} 
} 

public class MyStronglyTypedResultSet : MyBaseClass 
{ 
    public string FullName {get; set;} 
    public int Age {get; set;} 
} 

public void MyProblemMethod<T>(IEnumerable<T> allData, string officeToFind) 
{ 
    // How do I tell Linq that my <T> type is derived from 'MyBaseClass' so I can access the 'OfficeName' property? 

    IEnumerable<T> myData = allData.Where(c => c.OfficeName .ToLower().Equals(officeToFind.ToLower())); 
    MyUsefulObject.DataSource= myData; // This needs to have access to the properties in 'MyStronglyTypedResultSet' 
    MyUsefulObject.DataaBind(); 
} 
+1

使用'string.Equals(x,y,StringComparison.CurrentCultureIgnoreCase)'進行大小寫不敏感的比較。 ToLower比較最終會失敗。 – adrianm

回答

1

改變你的方法如下面

public void MyProblemMethod<T>(IEnumerable<T> allData, string officeToFind) where T : MyBaseClass 
{ 
    // How do I tell Linq that my <T> type is derived from 'MyBaseClass' so I can access the 'OfficeName' property? 

    IEnumerable<T> myData = allData.Where(c => c.OfficeName .ToLower().Equals(officeToFind.ToLower())); 
    MyUsefulObject.DataSource= myData; // This needs to have access to the properties in 'MyStronglyTypedResultSet' 
    MyUsefulObject.DataaBind(); 
} 
+0

我知道我錯過了一些東西!謝謝 –

+0

當綁定由Linq的延遲性質引起的IEnumerable時,我也得到一個空引用異常。這通過在查詢結尾處放置ToList()來解決。 –

2

可以使用OfType擴展方法。

public void MyProblemMethod<T>(IEnumerable<T> allData, string officeToFind) 
{ 
    // How do I tell Linq that my <T> type is derived from 'MyBaseClass' so I can access the 'OfficeName' property? 

    IEnumerable<T> myData = allData.OfType<MyBaseClass>.Where(c => c.OfficeName .ToLower().Equals(officeToFind.ToLower())); 
    MyUsefulObject.DataSource= myData; 
    MyUsefulObject.DataaBind(); 
} 
+0

這也工作謝謝 –