gpt4 book ai didi

c# - 返回自身类型的方法的接口(interface)

转载 作者:太空狗 更新时间:2023-10-29 18:04:56 25 4
gpt4 key购买 nike

我有一个类(class)

class Foo
{
Foo Bar()
{
return new Foo();
}
}

现在我想为它创建一个接口(interface)

class IFoo
{
??? Bar();
}

应该用什么代替问号?每个类都应该返回它自己的类型,而不是 Foo。

下面的解决方案有效但看起来不干净。我不明白为什么我必须指定同一个类两次,而且当前类型没有像“this”这样的东西

以后就是这样用的

class GenericClass<T> where T : IFoo
{
T foo = new T();
T item = foo.Bar();
}

最佳答案

你问:

The solutions below work but do not looks clean. I don't understand why i have to specify the same class twice, and there is nothing like "this" for the current type

之所以必须指定它两次,是因为 C# 缺少您需要的功能。你想要的是这样的:

interface IFoo
{
IFoo Bar();
}

class Foo : IFoo
{
Foo Bar() // should work since Foo is an IFoo, but it's not supported by C#
{
return new Foo();
}
}

从类型安全的角度来看,这应该可行(称为 return type covariance )。事实上,其他编程语言(如 C++ 或 Java)也支持这一点,请参阅 this example on Wikipedia .不幸的是,C# 不支持返回类型协变(甚至 C# 4.0 也不支持,它为泛型引入了协变),这就是为什么您必须使用其他答案中说明的“泛型解决方法”。 p>

协变返回类型和“this”类型是新版本 C# 的提议特性:

关于c# - 返回自身类型的方法的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3045671/

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