在泛型类型定义中更改泛型空性类型(在!或者?永远出去!)



我有以下扩展方法:

public static IRuleBuilder<TModel, TProperty> NotNull<TModel, TProperty>(this IRuleBuilderInitial<TModel, TProperty> ruleBuilder)

,其中TProperty可以是任何东西,但在这种情况下,我对引用类型感兴趣。假设它是一个IEnumerable<string>

我想重新定义上面的方法,以便它可以接受TPropertyIEnumerable<string>IEnumerable<string>?,但返回接口中的类型始终是IEnumerable<string>

有可能吗?任何类似的黑客攻击都是有效的。谢谢! .

在参数类型中使用TProperty?类型的参数,在返回类型中使用TProperty类型的参数就足够了。看到SharpLab。

#nullable enable
using System;
using System.Collections.Generic;
IRuleBuilderInitial<object, IEnumerable<string>?> initial = null!;
IRuleBuilder<object, IEnumerable<string>> next = initial.NotNull();
public static class C {
public static IRuleBuilder<TModel, TProperty> NotNull<TModel, TProperty>(
this IRuleBuilderInitial<TModel, TProperty?> ruleBuilder)
{
throw new NotImplementedException();
}
}
public interface IRuleBuilderInitial<TModel, TProperty>
{
}
public interface IRuleBuilder<TModel, TProperty>
{
}

请注意,对于可空引用类型和可空值类型的完全泛化是有限制的。上面的示例将完成您对引用类型的期望,但如果您想对值类型做类似的事情,我认为您需要拆分为两个重载,其中一个具有约束where TProperty : class,另一个具有约束where TProperty : struct

相关内容

最新更新