具有强制性 属性 的 C# 泛型类型
C# generic type with obligatory property
我正在构建一个用于 MongoDB 处理的通用 CRUD,但我在处理泛型类型时遇到了问题。问题是我需要使用类型的 属性 但泛型类型默认没有这个。
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 属性,但必须使用此 属性。谁能帮忙解决这个问题?
在 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
这里是伪代码:
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 语法...
我正在构建一个用于 MongoDB 处理的通用 CRUD,但我在处理泛型类型时遇到了问题。问题是我需要使用类型的 属性 但泛型类型默认没有这个。
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 属性,但必须使用此 属性。谁能帮忙解决这个问题?
在 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
这里是伪代码:
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 语法...