I have a solution where i get to map out all properties and sub-properties of an object into a Dictionary. Lets say I have something like these objects:
class MyClassA{
string info;
}
class MyClassB{
string info;
}
class MyClassC{
MyClassA a;
MyClassB b;
string something;
}
class MyClassD{
MyClassC c;
}
I created an utility to map out all the propreties so i can get something like:
MyClassD dObject = Something();
Dictionary<string, PropertyInfo> propertyMap = new Dictionary<string, PropertyInfo>();
propertyMap = buildPropertyMap(dObject );
where the string is the path and the PropertyInfo the actual property. The strings on the Map on this example would look like this (pseudo-output):
propertyMap.Keys={
c;
c.a;
c.b;
c.a.info;
c.b.info;
c.something;
}
This is a great way to tell what goes where when reading for example data from an excel file and not from xml-like things, like so:
ExcelTableC:
-----------------------
1|Ainfo|Binfo|Csomething|
-------------------------
2|value|value|valuevalue|
3|value|value|valuevalue|
-----------------------
It wall works great. Now thing is, this is all obviously inside a couple of loops and diferent functions (because of the Excel reading process) and i need later to get the key, this is, lets say I have this 'property' and I want the path (dont ask why):
// this method does not exist (pseudo-code)
PropertyInfo.GetPath; //it would return 'c.b.info' for ex. or 'c.a.info'
So i wanted to implement a class that extended PropertyInfo to add my methods.
But doing something like:
public class PropertyField : PropertyInfo
{
PropertyField parent;
string path;
// etc...
}
returns error because PropertyInfo is an abstract class and I would need to implement all inhereted members.
I can add 'abstract' to 'PropertyField' like this:
public abstract class PropertyField : PropertyInfo {}
But then when i try to cast it like this :
private void findProperties(Type objType)
{
PropertyInfo[] properties = objType.GetProperties();
for (int i=0; i< properties.Length; i++)
{
//PropertyInfo propertyInfo = properties[i];
PropertyField property = (PropertyField) properties[i];
//do something with it
}
}
will return the following error:
System.InvalidCastException: Unable to cast object of type
'System.Reflection.RuntimePropertyInfo' to type 'App.models.PropertyField'.
So the question is, how do I add these methods? If I cant inherit what can i do?
Aucun commentaire:
Enregistrer un commentaire