This is an interesting concept which i couldn’t figure out how to implement. (its related to a university assignment where i need to deploy the decorator pattern).
I’ve written rough C# code below which won’t compile however, Suppose, i have a class
Class A {
public int A { get; set; }
public string B { get; set; }
public float C { get; set; }
public string concatFields() {
string sample = null;
foreach (Field f in this) {
sample += f.ToString();
}
return sample;
}
}
How in terms would you achieve the concatFields method? Is there a way to iterate through the class’s fields (without knowing the names of the fields) and call ToString() on each.
In example B scenario, how would you apply the same method on all Fields provided they were the same type.
Cheers guys for the help, i’ve tagged this with C# but not sure what other tags could be applied
You can use reflection, iterate over metadata of your class, and pull fields through the reflection API. Obviously, there is a cost attached to that: using reflection is slower than accessing fields directly; sometimes, considerably. However, you can certainly do it. Here is an example:
FieldInfoclass exposes many useful properties, such asNameandType, letting you pick which fields to include in your processing, and which fields to ignore.