Reputation: 3637
I am working on a project that makes extensive use of XML config files, and I would like to take a few things to the next level with generic implementation of shared code.
Problem is, of my five classes, two handle a "description" grid view differently. This grid view shows objects of the appropriate type with various columns.
Also of note: the data is passed via a Data Record, so the GUI does not have direct access to the source object(s).
Here is my current "attempt" to get dynamic data, using a rather silly hack (that did not work)
GetObjectData( MyClass myObject, string[] dataToGet)
{
List<string> dataToReturn = new List<string>();
foreach (string propertyName in dataToGet)
{
try
{
Label tempLabel = new Label();
tempLabel.DataBindings.Add("Text", myObject, propertyName);
dataToReturn.Add(tempLabel.Text);
}
catch { dataToReturn.Add(""); }
}
}
There MUST be a way to do this, but I'm not sure what it would be called, or how to approach the issue.
Upvotes: 2
Views: 1958
Reputation: 36048
you could also use the dynamic type if you are using .net framework 4
public void GetObjectData(dynamic myObject, string[] dataToGet)
{
List<string> dataToReturn = new List<string>();
foreach (string propertyName in dataToGet)
{
try
{
dataToReturn.Add(Convert.ToString(myObject.propertyName));
}
catch
{ dataToReturn.Add("");
}
}
}
Upvotes: 1
Reputation: 18290
You can use Reflection to get property value in this manner:
public void GetObjectData(MyClass myObject, string[] dataToGet)
{
List<string> dataToReturn = new List<string>();
Type type = myObject.GetType();
foreach (string propertyName in dataToGet)
{
try
{
PropertyInfo pInfo = type.GetProperty(propertyName);
var myValue = pInfo.GetValue(myObject, null);
dataToReturn.Add(Convert.ToString(myValue));
}
catch
{ dataToReturn.Add("");
}
}
}
Hope this help you.. you can use dictionay
to save your return rather than list of string.
For Reference:
Use reflection to get the value of a property by name in a class instance
Set property Nullable<> by reflection
Reflection - get attribute name and value on property
Upvotes: 1