简体   繁体   English

是否可能有一个基类,其返回类型可以调整为基类的类型?

[英]Is it possible to have a base class with a return type that adjusts to the type of the base class?

Basically my setting is this: 基本上我的设置是这样的:

public abstract class BaseObject{
    public abstract BaseObject Clone();
}

public class DerivedObject : BaseObject{
    public DerivedObject Clone()
    {
        //Clone logic
    }
}

The above code doesn't compile because it isn't possible to change the return type when overriding a method. 上面的代码无法编译,因为在覆盖方法时无法更改返回类型。

Is it possible to achieve that every derived type's Clone method returns an argument of it's own type (maybe through generics)? 是否有可能实现每个派生类型的Clone方法都返回其自身类型的参数(也许通过泛型)?

Well, C# doesn't allow covariant return types as you've found... but you can use generics: 好吧,C#不允许像您发现的那样使用协变返回类型...但是您可以使用泛型:

public abstract class BaseObject<T> where T : BaseObject<T>
{
    public abstract T Clone();
}

public class DerivedObject : BaseObject<DerivedObject>
{
    public override DerivedObject Clone()
    {
         // ...
    }
}

This solution can be a pain in various ways - not least because it's hard to understand - but it can work reasonably well in many situations. 该解决方案可能会以多种方式带来痛苦-尤其是因为它难以理解-但在许多情况下都能很好地发挥作用。

EDIT: The reason I've included the constraint on T is so that BaseObject can call "its own" methods on instances of T , which is usually very handy. 编辑:我已经包括T上的约束的原因是,这样BaseObject可以调用的情况下,“自己的”方法T ,这通常是非常方便的。 If you don't need this though, you can lose the constraint. 如果您不需要它,则可以失去约束。

You can do something like this. 你可以做这样的事情。 Instead of returning default(T), return something based on the cloning logic. 而不是返回default(T),而是根据克隆逻辑返回某些内容。

public class MyBase<T>
{
    public T Clone()
    {
        return default(T);
    }
}

public class MyDerived : MyBase<MyDerived>
{
}

By the way, for object cloning I like to serialize the current object to memory using the binary serializer, then deserialize that memory back into a new instance. 顺便说一下,对于对象克隆,我喜欢使用二进制序列化器将当前对象序列化到内存,然后将该内存反序列化回一个新实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM