[英]C# : Use different fields from class in a generic method according to it's type parameter
我有一個具有多個泛型字段的類和一個必須根據其類型參數使用字段的泛型方法。 這可能嗎以及如何做到這一點?
public class MongoService
{
private readonly IMongoCollection<User> users;
private readonly IMongoCollection<Function> functions;
private readonly IMongoCollection<Group> groups;
public MongoService(IMongoSettings settings)
{
var client = new MongoClient(settings.ConnectionString);
var database = client.GetDatabase(settings.Database);
users = database.GetCollection<User>("user");
functions = database.GetCollection<Function>("function");
groups = database.GetCollection<Group>("group");
}
// User, Function and Group derives from MongoDocument
public async Task<T> GetById<T>(string id, string[] fieldToFetch) where T : MongoDocument
{
FilterDefinition<T> filter = Builders<T>.Filter.Eq("id", id);
ProjectionDefinition<T> projection = Builders<T>.Projection.Exclude("_id");
// SOMETHING should be :
// - users if GetById<User> is called
// - functions if GetById<Function> is called
// - groups if GetById<Group> is called
var document = await SOMETHING // ?
.Find(filter)
.Project<T>(projection)
.FirstOrDefaultAsync();
return document;
}
}
我只想添加一個私有方法來獲取相關集合,而不是將它們保留為類的成員:
private IMongoCollection<T> GetCollection<T>()
{
var collectionName = typeof(T).Name.ToLowerInvariant();
return database.GetCollection<T>(collectionName);
}
然后像這樣使用它:
public async Task<T> GetById<T>(string id, string[] fieldToFetch) where T : MongoDocument
{
// ... filter and projection code here ...
return await GetCollection<T>()
.Find(filter)
.Project<T>(projection)
.FirstOrDefaultAsync();
}
注意:這僅適用於將集合命名為與在 c# 中用於表示它的類型相同的類型,僅使用所有小寫字母 - 如問題中的代碼所示。
簡單。 您可以只使用: if (typeof(T) == typeof(Function))
。 但是如果這些領域都一樣,你應該更喜歡 Zohar 的解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.