2017-05-20 4 views
0

I A möchte eine Variable vom Typ B enthält jedoch einen Wert zu diesem varaible auf Zuweisung ich überprüfen wollen, ob es eine Instanz einer bestimmten Unterklasse von B. istTypprüfung Probleme

public class A { 

    public System.Type acceptedType; 

    public B target; 

    public A(System.Type t1){ 
     this.acceptedType = t1; 
    } 

    public bool connect(B b1){ 
     if(b1 is this.acceptedType){ 
      this.target = b1; 
      return true; 
     } 
     return false; 
    } 
} 

jedoch ich bekomme:

Unexpected Symbol 'this', erwartet 'Typ'

Is 'System.Type' die falsche Variablentyp oder bin ich das nur Missverständnis 'ist' Operator?

+1

'if (b1 ist typeof (this.acceptedType))' – Mardoxx

Antwort

1

arbeiten Dies wird nicht:

Foo fooObj = new Foo(); 
Foo fooObj2 = new Foo(); 
if (fooObj is fooObj2) // will not work 

Warum? Weil is einen Typ erfordert, KEINE Instanz. So wird diese Arbeit:

if (fooObj is Foo) 

bearbeiten

Hier ist, wie können Sie das tun, was Sie tun möchten:

Type fooType = typeof(String); 
if (fooType.IsAssignableFrom(typeof(int))) 
{ 
    Console.WriteLine("Will not show."); 
} 

if (fooType.IsAssignableFrom(typeof(string))) 
{ 
    Console.WriteLine("This will show."); 
} 

<== Fiddle With Me ==>

+0

Ich dachte, dass die Variable 'acceptedType' einen Typ und nicht nur eine Instanz enthalten würde. Wenn "System.type" nicht der richtige Variablentyp zum Speichern eines Typs ist, welcher Typ sollte die Variable sein? –

+0

@NicoS. Bitte siehe Bearbeiten. – CodingYoshi

1

Ich glaube, ich habe es herausgefunden .
Statt:

if(b1 is this.acceptedType) 

Ich verwende jetzt:

if(this.acceptedType.IsInstanceOfType(b1)) 

Und es scheint zu verhalten, wie ich es will.
Danke für den Hinweis, wo mein Fehler war!

Verwandte Themen