接口方法,返回其自己的类型 [英] Interface for method that returns its own type

查看:282
本文介绍了接口方法,返回其自己的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个情况我有一个类

 类Foo 
{
美孚栏( )
{
返回新的Foo();
}
}

现在我婉TOT为它创建一个接口

 类的IFoo 
{
?酒吧();
}



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



以下工作的解决方案,但没有看上去干净。我不明白为什么我必须指定两次相同的类,有没有像本为当前类型



这是我如何我以后使用它

 类GenericClass< T>其中T:IFoo的
{$ B $(B T)= foo的新T(); $ B $(B T)项目= foo.Bar();
}


解决方案

您问:




以下工作的解决方案,但没有看上去干净。我不明白为什么我必须指定两次相同的类,有没有像本为当前类型




你为什么要两次指定它的原因是因为C#缺少你所需要的功能。
你需要的是这样的:

 接口IFoo的
{
IFoo的酒吧( );
}

类Foo:IFoo的
{
美孚栏()//应该工作,因为foo是一个IFoo的,但它不是由C#
支持{
返回新的Foo();
}
}



从一个类型安全点,这应该工作(这就是所谓的返回类型的协方差)。事实上,其他编程语言如C ++或Java支持此功能,请参见维基百科这个例子。不幸的是,的返回类型的协方差的不是由C#(甚至不是C#4.0,它引入了泛型协方差),这就是为什么你必须使用在其他的答案中所示的仿制药替代方法的支持。



协变返回类型,以及这种式提出了C#的新版本的功能:




I have a situation where i have a class

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

Now i wan tot create an interface for it

class IFoo
{
    ??? Bar();
}

What should be in place of the question marks? Each class should return it's own type, not Foo.

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

This is how i am using it later

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

解决方案

You ask:

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

The reason why you have to specify it twice is because C# lacks the feature that you need. What you want is something like this:

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();
    }
}

From a type-safety point of view, this should work (it's called return type covariance). In fact, other programming languages such as C++ or Java support this, see this example on Wikipedia. Unfortunately, return type covariance is not supported by C# (not even C# 4.0, which introduced covariance for generics), which is why you have to use the "generics workaround" illustrated in the other answers.

Covariant return types as well as a "this" type are proposed features for new versions of C#:

这篇关于接口方法,返回其自己的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆