2010-06-06 14 views
5

Mam dwie klasy, klasę podstawową i klasę podrzędną. W klasie bazowej i określić ogólny sposób wirtualny:Dziwne generyczne błędy kompilacji

protected virtual ReturnType Create<T>() where T : ReturnType {}

potem w mojej klasie dzieci próbuję to zrobić:

protected override ReturnTypeChild Create<T>() // ReturnTypeChild inherits ReturnType 
{ 
    return base.Create<T> as ReturnTypeChild; 
}

Visual Studio daje ten dziwny błąd:

The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Create()'. There is no boxing conversion or type parameter conversion from 'T' to 'ReturnType'.

Powtarzanie klauzuli where na override dziecka również powoduje błąd:

Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly

Co ja tu robię źle?

+0

Czy to powinno być "chronione zastąpić BarChild Foo ()'? Czy potrafisz podać prawdziwe imiona? Foo i Bar ranią moją głowę. – Kobi

+0

I nie powinien to być powracający base.Foo jako BarChild() ;? – GenericTypeTea

+1

Twój kod ma wiele problemów (np. Twoja nadpisana metoda nie ma swojego parametru ogólnego, twoja instrukcja return ma błędy w niewłaściwym miejscu itd.). Bardziej prawdopodobne jest uzyskanie pomocnych odpowiedzi, jeśli stworzysz minimalną reprodukcję problemu, który ma naprawione wszystkie oczywiste problemy. – kvb

Odpowiedz

3

To działa. Trzeba było dokonać typ zwracany Generic:

public class BaseClass { 
    public virtual T Create<T>() where T : BaseClass, new() { 
    var newClass = new T(); 
    //initialize newClass by setting properties etc 
    return newClass; 
    } 
} 

public class DerivedClass : BaseClass { 
    public override T Create<T>() { 
    var newClass = base.Create<T>(); 
    //initialize newClass with DerivedClass specific stuff 
    return newClass; 
    } 
} 

void Test() { 

DerivedClass d = new DerivedClass() ; 
d.Create<DerivedClass>(); 
} 

Są pewne podstawowe C# override rules:

The overridden base method must have the same signature as the override method.

Oznacza to ten sam typ zwracanej same argumenty i metody.

+0

Czy możesz edytować jeszcze 1 raz? klasy wymagają wcięcia do poprawnego formatowania AFAICT –

+0

Ups, poprawione. –

2

Twoje przesłonięcie nie może zmienić typu zwracanego, nawet jeśli typ zwracany pochodzi z typu zwracanego przez metodę klasy podstawowej. Musisz zrobić coś podobnego do tego, co zrobił Igor powyżej, i stworzyć typ zwrotny.

Powiązane problemy