gpt4 book ai didi

c# - 如何编写包装类以使用部分泛型类型推断?

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

这与 this question 有关.

我想创建一个通用的包装类:

public abstract class Wrapper<T>
{
internal protected T Wrapped { get; set; }
}

具有以下扩展:

public static class WrapperExtensions
{
public static W Wrap<W,T>(this T wrapped) where W:Wrapper<T>,new()
{
return new W {Wrapped = wrapped};
}

public static T Unwrap<T>(this Wrapper<T> w)
{
return w.Wrapped;
}
}

现在假设一个具体的包装器:

public class MyIntWrapper : Wrapper<int>
{
public override string ToString()
{
return "I am wrapping an integer with value " + Wrapped;
}
}

我想像这样调用 Wrap 扩展:

MyIntWrapper wrapped = 42.Wrap<MyIntWrapper>(); 

这是不可能的,因为在 c# 中我们需要为 Wrap 扩展提供两种类型的参数。(全有或全无)

显然,部分推理在 F# 中是可能的。

上面的代码在 F# 中看起来如何?

是否可以在 C# 中使用它?

最佳答案

显然在 F# 中可以进行部分推理。

是的,在您的示例中只需要指定 W。 T 将被推断。


上面的代码在 F# 中看起来如何?

[<AbstractClass>]
type Wrapper<'a>() =
[<DefaultValue>]
val mutable internal Wrapped : 'a

let Wrap<'W,'T when 'W :> Wrapper<'T> and 'W: (new: unit -> 'W)> (wrapped: 'T): 'W =
let instance = new 'W()
instance.Wrapped <- wrapped
instance

let Unwrap (w: Wrapper<_>) = w.Wrapped

type MyIntWrapper() =
inherit Wrapper<int>()
override this.ToString() =
sprintf "I'm wrapping an integer with value %d" this.Wrapped

并且您可以通过这种方式从 F# 交互式调用 Wrap

> let wrapped = Wrap<MyIntWrapper,_> 5;;
val wrapped : MyIntWrapper = I'm wrapping an integer with value 5

在我看来,这在 F# 中不是很惯用,我宁愿使用区分联合和模式匹配来包装/展开,但我不知道您的具体情况是什么。


是否可以从 C# 使用它?

当然可以,但是如果您从 C# 调用 Wrap,您将返回到 C# 类型推断并且必须指定第二个类型参数。

关于c# - 如何编写包装类以使用部分泛型类型推断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14058654/

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