如何定义返回派生类类型的实例的一般方法? [英] How to define a generic method that returns an instance of the deriving class type?

查看:166
本文介绍了如何定义返回派生类类型的实例的一般方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有两个类执行相同的功能:

  class HDD:Disk 
{
public HDD RMA()
{
HDD newHDD = RMAService.Exchange(this);
return newHDD;
}
}
类SSD:磁盘
{
public SSD RMA()
{
SSD newSSD = RMAService.Exchange ;
return newSSD;
}
}

我想要的是实现RMA函数基类,但保持强类型的返回值,以便用户可以通过函数签名确定他们正在收回他们发送的磁盘类型!






我到目前为止所做的尝试:



这种类型定义虽然丑陋。任何创建自己的Disk类或引用磁盘的人都很难知道如何正确使用类型。



还没有办法限制类型参数正好是被定义的类。它似乎很奇怪,没有一个专门的方法声明一个基本类中的属性或方法,其中编译时类型是任何派生类型是。

解决方案

我刚刚想出了这个解决方案使用扩展方法,这看起来好多了。任何理由为什么这不会工作在编译时如何工作?

  public abstract class Disk 
{
public Disk(){}
}
public static class Disk_Extension_Methods
{
public static T RMA< T>(this T oldDisk)其中T:Disk
{
T newDisk = RMAService.Exchange(oldDisk)
return newDisk;
}
}

这让您可以去:

  public class HDD:Disk {} 
public class SSD:Disk {}

HDD newHDD = someHDD。 RMA();


For instance, I have two classes performing the same function:

class HDD : Disk
{
    public HDD RMA()
    {
       HDD newHDD = RMAService.Exchange(this);
       return newHDD;
    }
}
class SSD : Disk
{
    public SSD RMA()
    {
       SSD newSSD = RMAService.Exchange(this);
       return newSSD;
    }
}

What I would like is to implement the RMA function in the base class, but maintain the strongly typed return value, so that the user can be certain by the function signature that they are getting back the type of disk they sent in!


What I have tried so far:

(see solutions below)

This type definition is ugly though. Anyone creating their own Disk class or a reference to a Disk would have a hard time knowing how to correctly use the type.

There's also no way to constrain the type argument to be exactly the class being defined. It just seems odd that there isn't a specialized way of declaring a property or method in a base class where the compile time type is whatever the derived type is.

解决方案

I just came up with this solution using an extension method, which appears much better. Any reason why this wouldn't work how it appears to work at compile time?

public abstract class Disk
{
    public Disk() { }
}
public static class Disk_Extension_Methods
{  
    public static T RMA<T>(this T oldDisk) where T : Disk
    {
        T newDisk = RMAService.Exchange(oldDisk)
        return newDisk;
    }
}

Which allows you to go:

public class HDD : Disk { }
public class SSD : Disk { }

HDD newHDD = someHDD.RMA();

这篇关于如何定义返回派生类类型的实例的一般方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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