Frage

I have several classes that inhabit from this class:

 public abstract class Class1
{
    private string _protocol;
    private static List<Plus> _class1Objects;

    public string Protocol
    {
        get { return _protocol; }
        set { _protocol = value; }
    }

    public static List<Plus> Class1Objects
    {
        get { return _class1Objects; }
        set { _class1Objects = value; }
    }
}

And the derive class:

public class Class2 : Plus
{
    public bool name;
    public int id;

}

public Webmail(string name, int id)
{
    if (Class1Objects == null)
        Class1Objects = new List<class1>();

    .....

    Class1Objects.Add(this);
}

And after my list is full of Class1Objects:

for (int i = 0; i < Class1.Class1Objects.Count; i++)
{
    if (Class1.Class1Objects[i].GetType() == typeof(Class2))
    }   
         (Class2)Class1.Class1Objects[i]. 
    }
}

Here after (Class2)Class1.Class1Objects[i]. i cannot see my Class2 memners

War es hilfreich?

Lösung

You need one additional paranthese:

((Class2)Class1.Class1Objects[i]).

At the moment it is read as the following:

(Class2)(Class1.Class1Objects[i].) //<= at the '.' it is still a class1

BUT as David said in his comment: If all are of type Class2 it should be a collection of that type and if not you should check the type, altogether with foreach:

foreach(var item in Class1.Class1Objects)
{
    if(item is Class2)
        ((Class2)Class1.Class1Objects[i]).
}

Andere Tipps

It would be cleaner to use as:

for (int i = 0; i < Class1.Class1Objects.Count; i++)
{
    var c2 = Class1.Class1Objects[i] as Class2;
    if (c2!=null)
    }   
         c2.<whatever was meant to come after the .>
    }
}

You might also want to consider switching to foreach unless there's a specific reason you want to manually extract each element from the List, e.g. if you're actually storing new values back into the list.

The correct syntax would be:

((Class2)Class1.Class1Objects[i]).name;

Because in your case, when you type something like this:

(Class2)Class1.Class1Objects[i].name;

You try to access the member name of Class1.Class1Objects[i], and only after that you try to cast it to Class2.

Also, the whole loop would be much simpler if you used foreach:

using System.Linq;

foreach(Class2 c in Class1.Class1Objects.OfType<Class2>())
{
    Console.WriteLine(c.name); // or whatever you need to do with it
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top