我正在為 MongoDB 處理構建一個通用 CRUD,但我遇到了 generic type 的問題。問題是我需要使用該型別的屬性,但泛型型別默認沒有這個屬性。
public static Task UpdateConfig<T>(T config)
{
IMongoCollection<T> collection = ConnectToMongo<T>("collectionName", "dataBase");
FilterDefinition<T>? filter = Builders<T>.Filter.Eq("Id", config.Id);
return collection.ReplaceOneAsync(filter, config, new ReplaceOptions { IsUpsert = true });
}
問題在于:
FilterDefinition<T>? filter = Builders<T>.Filter.Eq("Id", config.Id);
配置不附帶 Id 屬性,但必須使用此屬性。有人可以幫忙嗎?
uj5u.com熱心網友回復:
在 dot net 中處理此類需求的方法是使用通用約束和介面:
public interface IConfig // You might want to change this name
{
int Id {get;} // data type assumed to be int, can be anything you need of course
}
....
public static Task UpdateConfig<T>(T config) where T : IConfig
... rest of the code here
uj5u.com熱心網友回復:
偽代碼在這里:
public interface IId {
public int Id {get;set;}
}
public static Task UpdateConfig<T>(T config) where T : IId
{
IMongoCollection<T> collection = ConnectToMongo<T>("collectionName", "dataBase");
FilterDefinition<T>? filter = Builders<T>.Filter.Eq("Id", config.Id);
return collection.ReplaceOneAsync(filter, config, new ReplaceOptions { IsUpsert = true });
}
這應該有效嗎?除非我完全搞砸了 where 語法......
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/410185.html
標籤:
