gpt4 book ai didi

C# 泛型 : How to avoid code duplication when using struct constraints and nullables in lambda expressions

转载 作者:太空狗 更新时间:2023-10-30 01:10:05 26 4
gpt4 key购买 nike

假设我有一个函数,例如:

    public TProperty Foo<TClass, TProperty>(TClass instance, Expression<Func<TClass, TProperty>> expression)
{
...
}

但后来我意识到它应该只用于值类型,所以我添加了一个约束

    public TProperty Foo<TClass, TProperty>(TClass instance, Expression<Func<TClass, TProperty>> expression)
where TProperty : struct
{
...
}

但随后我发现这不会让我传递采用可为 null 的 TProperty 的表达式。我认为处理此问题的唯一方法是执行以下操作:

    public TProperty Foo<TClass, TProperty>(TClass instance, Expression<Func<TClass, TProperty?>> expression)
where TProperty : struct
{
...
}

但现在我不得不维护两种方法来做完全相同的事情,除了一种处理可空值,而另一种不处理。

此外,我无法将它们提取到通用方法中,因为即使存在从 T 到 T? 的转换,显然也没有从

Expression<Func<T1, T2>>

Expression<Func<T1, T2?>>

如果这些方法的主体很复杂,我真的不想维护它们的两个独立版本,尤其是当它实际上是一整套函数时。

有没有办法避免这种代码重复,并且仍然让编译器强制表达式必须以值类型或可空类型结尾?

(我目前使用的是 C# 3.5,但如果更新的版本提供了干净的解决方案,我愿意接受它们。)

最佳答案

根据您对表达式所做的操作,您可以使两个重载都调用一个采用(未类型化)LambdaExpression 的私有(private)覆盖。

关于C# 泛型 : How to avoid code duplication when using struct constraints and nullables in lambda expressions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5412839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com