繁体   English   中英

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 语法......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM