Using reflection to get the property's static value, concatenation of the derived and base class

I will do my best to explain my vision here. This is a very outdated example. I have several different types of Bags, and they all have their own special type Marble. Each type Marblehas its own set of aliases ( strings).

Unfortunately, there are other things besides "Marble in a bag", so generics will not help me.

// Bags
abstract class Bag {
    protected Type MarbleType { get; }
    protected List<Marble> _marbles;

    public void DumpBag()
    { ... }
}
class RedBag : Bag {
    override Type MarbleType { get { return typeof(RedMarble); } }
}
class BlueBag : Bag {
    override Type MarbleType { get { return typeof(BlueMarble); } }
}

// Marbles
abstract class Marble {
    public static IEnumerable<string> Nicknames {
        get {
            return new List<string>() {
               "Marble", "RollyThing"
            }
        }
    }
}
class RedMarble : Marble {
    public static IEnumerable<string> Nicknames {
        get {
            return new List<string>(Marble.Nicknames) {
                "Ruby"
            };
        }
    }
}
class BlueMarble : Marble { ... }

So now we get to the details, the implementation DumpBag(). Consider the following call:

Bag b = new RedBag();
b.GetMarbles();
b.DumpBag();

I would like it to print:

Bag of Marbles (aka "Marble", "RollyThing", Ruby"):
- Marble 1
- Marble 2
...

, Bag Marble, - . Nicknames Marble, RedMarble.

DumpBag " ". DumpBag :

public void DumpBag() {
    PropertyInfo pi = this.MarbleType.GetProperty("Nicknames", BindingFlags.Static);
    IEnumerable<string> nicknames = pi.GetValue(null, null);  // No instance

    StringBuilder sb = new StringBuilder("Bag of Marbles (aka ");
    foreach (string nn in nicknames)
        sb.Append("\"" + nn + "\", ");
    Console.WriteLine(sb.ToString());

    ...
}

:

  • ? , ( ) , .
  • (), RedMarble.Nicknames Marble.Nicknames. new?
+3
1

, , , - :

(List<string>)this.MarbleType.GetProperty("Nicknames").GetValue(null, null);

, .

, , , - , . - .


, ?

, , :

abstract class Bag<T> where T:marble {
    public void DumpBag()
    { 
        // here you can use
        // (IEnumerable<string>)typeof(T).GetProperty("Nicknames").GetValue(null, null);
    }
}

class RedBag : Bag<RedMarble> {
}

class BlueBag : Bag<BlueMarble> {
}

, , , , Marble RedMarble BlueMarble, DumpBag Nicknames, .

+3

All Articles