Как Наследовать метод, но с другим типом возврата?

IPhone использует Objective C, Java Blackberry SE с функциональностью RIM и Android другая пользовательская версия Java. Я мог возможно видеть, как Вы могли объединить последние два, но нет никакой функциональности (не перепрошивая) под управлением JAVA-приложений на iPhone.

лучший выбор, который я видел до сих пор, является чем-то как Qt, который будет работать на Windows CE, почти наверняка вскоре Symbian, некоторые платформы Java и три главных настольных OSS

9
задан John Rudy 12 November 2009 в 16:54
поделиться

9 ответов

Вам необходимо создать защищенный виртуальный метод для DoSomethingAndReturnNewObject , чтобы использовать:

class ClassA
{
    protected virtual ClassA Create()
    {
        return new ClassA()
    }

    public ClassA DoSomethingAndReturnNewObject()
    {
        ClassA result = Create();
        // Do stuff to result
        return result;
    }
}

class ClassB : ClassA
{
     protected override ClassA Create() { return new ClassB(); }
}

class ClassC : ClassA
{
     protected override ClassA Create() { return new ClassC(); }
}

Обратите внимание, что возвращаемый тип остается ClassA, но тип экземпляра объекта будет конкретным классом.

6
ответ дан 4 December 2019 в 11:05
поделиться
class ClassA<T> where T : ClassA<T>, new()
{
    public T DoSomethingAndReturnNewObject()
    {
        return new T();
    }
}

class ClassB : ClassA<ClassB> { }

class ClassC : ClassA<ClassC> { }

Тест:

ClassB b1 = new ClassB();

ClassB b2 = b1.DoSomethingAndReturnNewObject(); // returns instance of ClassB
2
ответ дан 4 December 2019 в 11:05
поделиться

Я наконец придумал следующее решение. В моем случае это достаточно полезно, но предполагается, что ClassA знает о своих производных и ограничен этими двумя вариантами. Не совсем высокоуровневое мышление, но оно работает. :)

ClassA
{
    public ClassA DoSomethingAndReturnNewObject()
    {
        if (this.GetType() == typeOf(ClassB))
        {
            return new ClassB(values);
        }
        else
        {
            return new ClassC(values):
        }
    }    
}

ClassB : ClassA
{}

ClassC : ClassA
{}
0
ответ дан 4 December 2019 в 11:05
поделиться

Нет, упомянутая вами функция называется ковариацией возвращаемого типа . Он не поддерживается в C #.

8
ответ дан 4 December 2019 в 11:05
поделиться

What you're describing is a covariant return type and is not supported in C#.

However, you could create ClassA as an open generic and have the closed generic inheritors return their own type.

Example:

public abstract class ClassA<T> where T: ClassA<T>, new()
{
    public abstract T DoSomethingAndReturnNewObject();
}

public class ClassB: ClassA<ClassB>
{
    public override ClassB DoSomethingAndReturnNewObject()
    {
        //do whatever
    }
}
6
ответ дан 4 December 2019 в 11:05
поделиться

Well, the correct answer is no and, generally, this is a bad idea. If you are returning something completely different, find another way.

However, if you aren't returning something completely different, an interface can solve your issue. Instead of returning a class, return an interface and have classes A, B, and C return objects that implement that interface in the way they see fit.

0
ответ дан 4 December 2019 в 11:05
поделиться

This isn't inheritance, because the return type of the method is part of its signature. You're not changing the method, you'd be creating an entirely new one.

You do have some options. You could, for example, make the method DoSomethingAndReturnNewObject a generic-based method, and have it return its generic type. This is probably the most direct path to the exact behavior for which you're looking.

The other alternative is to leave the method signatures as-is, and have the subclass methods return instances of ClassB and ClassC. Then the client code would need to be responsible for casting in order to use those objects as their appropriate derived classes.

Is there some reason the common interface of ClassA doesn't suffice? Polymorphism will, if you have derived and overridden virtual members correctly, provide you with the correct functionality if you're only using the ClassA members.

0
ответ дан 4 December 2019 в 11:05
поделиться

Maybe generics will be your saviour. Take a look at this link: C# Generics Part 3/4: Casting, Inheritance, and Generic Methods

bstract class  B<T> {
   public abstract T Fct(T t);
}
class D1 : B<string>{
   public override string Fct( string t ) { return "hello"; }
}
class D2<T> : B<T>{
   public override T Fct(T t) { return default (T); }
}
0
ответ дан 4 December 2019 в 11:05
поделиться

I think that you need to create a new function with the new return type and call inside the other function, and manipulate the type returned. otherwise it will no be logical ! (with the definition/idea of inheritance)

-1
ответ дан 4 December 2019 в 11:05
поделиться
Другие вопросы по тегам:

Похожие вопросы: