簡體   English   中英

Linq如何擴展\\覆蓋現有的toList()方法

[英]Linq how to Extend\Override existing toList() Method

我正在使用Linq到Sql。 我想在調用(System.Linq)toList()方法時打開事務范圍。 因此,我試圖通過創建自定義擴展類並由此創建toList()的新版本來覆蓋默認的toList()方法。 但是在自定義toList()擴展中,我想調用現有的默認(system.linq)ToList()方法。 但我無法做到這一點。 請參見以下示例:

碼:

public static int GetRecordsWithNoChangeToQuery()
{
    string connection = ConfigurationManager.ConnectionStrings["EventConn"].ConnectionString;
    using (var ctx = new EventsDataContext(connection))
    {
        var records = (from m in ctx.Event select m).ToList(); //calling custom extension method
        return records.Count();
    }
}

LinqExtenionHeler

public static class LinqExtension
{
    public static TransactionScope CreateLockTransaction()
    {
        var options = new TransactionOptions
        {
            IsolationLevel = IsolationLevel.ReadCommitted
        };
        return new TransactionScope(TransactionScopeOption.Required, options);
    }

    //custom extension method
    public static List<T> ToList<T>(this IEnumerable<T> query)
    {
        using (TransactionScope ts = CreateLockTransaction())
        {
            return query.ToList(); //fails, not able to call system.linq .toList method
        }
    }
}

在上面的代碼中,當我調用query.ToList()時,將引發錯誤。 由於它正在嘗試自我調用,那么如何從相同名稱的自定義擴展方法中調用默認(syste.linq)query.toList()?

擴展方法只是調用公共靜態方法的一種好方法。 您仍然可以將其稱為正常方式,有時甚至必須如此。

 return System.Linq.Enumerable.ToList(query); 

但是,我支持尖叫“等等,為什么要這樣做?”的評論。 看來這不是最理想的方法。 也許您應該問一個關於您的問題的更開放的問題,以獲得針對您的全局問題的更好的答案,這只是解決您的本地句法問題。

您為List創建的擴展方法,它將在內部對其自身進行調用,因為查詢的類型是IEnumerable,並且將通過異常或處於死鎖狀態。 因此對於ToList擴展方法,您可以做一件事,即傳遞的參數可以是IQueryable。 所以synatax as-

public static List<T> ToList<T>(this IQueryable<T> query)
{ using (TransactionScope ts = CreateNoLockTransaction()) { return query.AsEnumerable().ToList(); } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM