簡體   English   中英

如何使用IOptions <T> 作為通用方法中的通用參數

[英]How to use IOptions<T> as a generic parameter in a generic method

我正在嘗試創建一個使用IOptions<T>作為參數的通用方法,但是代碼似乎無效。

Visual Studio顯示以下消息:

TConfig必須是具有非參數構造函數的非抽象類型,才能將其用作通用類型或方法'IOptions<TOptions>'的參數“ TOption 'IOptions<TOptions>'

任何有關如何解決此問題的建議將不勝感激。 謝謝!!

public static IServiceCollection AddConfigurations<TConfig>(
    this IServiceCollection services, IConfiguration configuration, 
    IOptions<TConfig> options) 
    where TConfig : class
{
}

問題是, IOptions具有以下IOptions

where TOptions : class, new()

因此,您也需要此約束( new() ):

public static IServiceCollection AddConfigurations<TConfig>(
    this IServiceCollection services, IConfiguration configuration, 
    IOptions<TConfig> options) 
    where TConfig : class, new()
{
}

IOptions<T>的定義中查看對T的約束。 由於AddConfigurations<TConfig>使用IOptions<TConfig>因此至少需要對TConfig這些限制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM