C# 有没有办法创建一个可以返回不同类型的方法,谓词<;BsonDocument>;或过滤器定义<;b声控文档>;?
我有以下代码:C# 有没有办法创建一个可以返回不同类型的方法,谓词<;BsonDocument>;或过滤器定义<;b声控文档>;?,c#,generics,filter,predicate,bson,C#,Generics,Filter,Predicate,Bson,我有以下代码: IMongoCollection<BsonDocument> collection = _database.GetWriteCollection(typeName); collection.DeleteMany(x => includedIdentifiers.Contains((string)x["_id"])); List<BsonDocument> allRecords = await col
IMongoCollection<BsonDocument> collection = _database.GetWriteCollection(typeName);
collection.DeleteMany(x => includedIdentifiers.Contains((string)x["_id"]));
List<BsonDocument> allRecords = await collection.Find(x => true)
.ToListAsync();
allRecords.RemoveAll(x => includedIdentifiers.Contains((string)x["_id"]));
错误是
严重性代码说明项目文件行抑制状态
错误CS1503参数1:无法从“System.Predicate”转换为“MongoDB.Driver.FilterDefinition”SalesforceCache C:\projects\Salesforce缓存和Sync\SalesforceCache\Salesforce\SalesforcSyncWorker.cs 488 Active
是否有一种方法(可能添加一些类型参数)可以使一个函数满足这两种需要?在C#中,是否有一种方法可以创建一个可以返回一个类或另一个类的方法?
对问题标题的简短回答:没有,但是…
一个方法不能返回一个唯一的类型或另一个完全不同的没有共同点的类型
我们只能返回一个整型数值,比如int,或者一个值类型实例,比如struct,或者一个引用值,比如类,或者元组,还有一个接口
除非我们有一个基类或这些类型的通用接口
例如,如果谓词
或过滤器定义
实现了IMyInterface
,我们可以将一个或另一个对象作为此接口返回:
IMyInterface MyMethod()
{
if ( ... )
return (IMyInterface)new Predicate<BsonDocument>();
else
return (IMyInterface)new FilterDefinition<BsonDocument>();
}
在这里抛出异常非常谨慎,可能会被忽略,也可能不会…@OlivierRogier,我怀疑你是对的,但我将保留这个问题,以防万一。创建一个扩展方法,将其中一个转换为另一个。叫做IsBaseIDS(IDS)。ASMMOGOFILTER()。@ WikTrutZyChLA,这比我知道的要多一些,但是如果你能在下面说明,我会很乐意考虑的。感谢详细、合理的回复和链接。在我看来,“hack”会产生比它解决的问题更多的问题,特别是因为我只想找出一个短表达式,它看起来是重复的,即使底层类型不同。(但是,FWIW,我想我会在元组前面使用“任一”类型来表示类似的内容。)
private Predicate<BsonDocument> IsContained(HashSet<string> includedIdentifiers)
{
return x => includedIdentifiers.Contains((string)x["_id"]);
}
IMyInterface MyMethod()
{
if ( ... )
return (IMyInterface)new Predicate<BsonDocument>();
else
return (IMyInterface)new FilterDefinition<BsonDocument>();
}
(Predicate<BsonDocument> predicate, FilterDefinition<BsonDocument> filterdefinition) MyMethod()
{
if ( ... )
return (new Predicate<BsonDocument>(), null);
else
return (null, FilterDefinition<BsonDocument>());
}
var result = MyMethod();
if ( result.predicate != null && result.filterdefinition != null )
throw new SystemException("Two instances provided: only one is expected.");
else
if (result.predicate != null)
{
...
}
else
if (result.filterdefinition != null)
{
...
}
else
throw new SystemException("No instance provided: one is expected.");