Question

I am trying to get the underlying type from a linq query running against the type's GetFields method. In my example, i have:

string mClass = "Computer"; //match string
var t = typeof(SystemMonitoringClass);
var monitoringClass = (SystemMonitoringClass)t.GetFields().First(x => x.Name == mClass); 

The casting in my 3rd line fails as i can't convert the returning type FieldInfo into what i am looking for. So after finding the right field, how can i get the actual object. This workaround is due to the new SCOM 2012 SDK changing SystemMonitoringClass from an enum to a class. If someone has a better approach to match a string and get the actual monitoring object or field in this case, that would also work.

http://msdn.microsoft.com/en-us/library/hh326622.aspx

Was it helpful?

Solution

You need to separate the concepts of "the field" from "the value of that field for a particular instance". You want FieldInfo.GetValue, e.g.

var monitoringClass = (SystemClass) field.GetValue(null);

EDIT: I note that SystemMonitoringClass.Computer is actually declared to return a value of type SystemClass, not SystemMonitoringClass - so you may want to change your cast appropriately, as I have above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top