[英]Call Class Method Rather Than Extension Method
我正在使用MongoDB C#驅動程序和NSubstitute。 我需要在IMongoCollection類上模擬FindAsync方法。 問題是存在一個具有完全相同簽名的IMongoCollectionExtension類。 當我嘗試模擬FindAsync方法時,它會調用擴展方法,該擴展方法會由於“ Secure.IsNotNull”調用而引發異常。
有沒有一種方法可以確保調用類方法而不是擴展方法? 現在還不行。 它們甚至位於同一名稱空間中。
我試圖通過測試調用它的示例。
_collection = Substitute.For<IMongoCollection<DirectoryObject>>();
_database.GetCollection<DirectoryObject>(Constants.DirectoryObjectCollection).Returns(_collection);
_collection.FindAsync(Arg.Any<FilterDefinition<DirectoryObject>>(), null, default(CancellationToken)).Returns(cursor);
方法簽名:
Task<IAsyncCursor<TProjection>> FindAsync<TProjection>(FilterDefinition<TDocument> filter, FindOptions<TDocument, TProjection> options = null, CancellationToken cancellationToken = default(CancellationToken));
擴展方法簽名:
public static Task<IAsyncCursor<TDocument>> FindAsync<TDocument>(this IMongoCollection<TDocument> collection, FilterDefinition<TDocument> filter, FindOptions<TDocument, TDocument> options = null, CancellationToken cancellationToken = default(CancellationToken))
IntelliSense的屏幕快照,提示我正在調用擴展方法。
編輯:
將模擬方法調用更改為此可以解決此問題。 簽名並不完全相同。 該擴展名沒有其他投影和文檔類型。
_collection.FindAsync<DirectoryObject>(Arg.Any<FilterDefinition<DirectoryObject>>(), null, default(CancellationToken)).Returns(cursor);
如果其他人認為他們有此問題,請參考,您可以! 在實例方法和擴展方法之間的命名沖突時,將調用實例方法。
如果確實需要優先選擇調用哪個方法,則實際上存在一個相反的問題,即使用其聲明類直接調用擴展方法。
例如,名稱沖突如下:
public static class ObjectExt
{
public static string ToString(this object o) => "";
}
您可以消除歧義為:
instance.ToString(); // call the instance method
ObjectExt.ToString(instance); // call the extension method
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.