tags:

views:

3983

answers:

5

I trying implement in my code this example link but in

private object GetSourceValue(string propertyName) {}

he have a switch comparing various types. I want remove this types and properties and have a only GetSourceValue does can get source of property using only a string in parameter. I want pass class and property in string e resolve the value object of property.

Its Possible?

+11  A: 
 public static object GetPropValue( object src, string propName )
 {
     src.GetType( ).GetProperty( propName ).GetValue( src, null );
 }

Of course, you will want to add validation and whatnot, but that is the gist of it.

Ed Swangren
Yes i know i can use like you say. But i don't want pass src object. I want pass only a string with name like "Class1.Prop1" and give me the Prop1 value of Class1 class.
pho3nix
You asked in your question "I want pass class", I assume that meant "object" and not "class" since "class" makes little sense. Why would you vote this down? Can you not figure out how to modify this code to use "this" instead? Is it a static property of a class? You need to be more specific then, this is the correct answer.
Ed Swangren
A: 

How about something like this:

public Object GetPropValue(String name, Object obj) {
    foreach (String part in name.Split('.')) {
        if (obj == null) { return null; }

        Type type = obj.GetType();
        PropertyInfo info = type.GetProperty(part);
        if (info == null) { return null; }

        obj = info.GetValue(obj, null);
    }
    return obj;
}
jheddings
A: 

You never mention what object you are inspecting, and since you are rejecting ones that reference a given object, I will assume you mean a static one.

using System.Reflection;
public object GetPropValue(string prop)
{
    int splitPoint = prop.LastIndexOf('.');
    Type type = Assembly.GetEntryAssembly().GetType(prop.Substring(0, splitPoint));
    object obj = null;
    return type.GetProperty(prop.Substring(splitPoint + 1)).GetValue(obj, null);
}

Note that I marked the object that is being inspected with the local variable obj. null means static, otherwise set it to what you want. Also note that the GetEntryAssembly() is one of a few available methods to get the "running" assembly, you may want to play around with it if you are having a hard time loading the type.

Guvante
+2  A: 

what about using the CallByName of the visualbasic namespace? which is reflection.

using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;

and then

Versioned.CallByName(this, "method/function/prop name", CallType.Get).ToString();
Fredou
A: 

Dim NewHandle As YourType = CType(Microsoft.VisualBasic.CallByName(ObjectThatContainsYourVariable, "YourVariableName", CallType), YourType)

Kyle