动态访问类的属性

时间:2013-07-15 06:57:55

标签: c#-4.0 casting

您好我必须使用相同属性的不同类,我想动态访问我的类的peoperties。

public Class1
{
public const prop1="Some";
}
public Class2
{
 public const prop1="Some";
}

在我的代码中,我得到了我的类名

string classname="Session["myclass"].ToString();";//Say I have Class1 now.

我想获得prop1值。

Something like
 string mypropvalue=classname+".prop1";//my expected result is Some 

///      输入typ = Type.GetType(classname);

请帮我解决这个问题

2 个答案:

答案 0 :(得分:0)

Reflection

var nameOfProperty = "prop1";
var propertyInfo = Class1Object.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);

for static:

var nameOfProperty = "prop1";
var propertyInfo = typeof(Class1).GetProperty("prop1", BindingFlags.Static);
var value = propertyInfo.GetValue(myObject, null);

Class reference from string

编辑(我做了例子):

class Program
    {
        static void Main(string[] args)
        {

            var list = Assembly.Load("ConsoleApplication4").GetTypes().ToList();
            Type ty = Type.GetType(list.FirstOrDefault(t => t.Name == "Foo").ToString());
            //This works too: Type ty = Type.GetType("ConsoleApplication4.Foo");
            var prop1 
                 = ty.GetProperty("Temp", BindingFlags.Static | BindingFlags.Public);


            Console.WriteLine(prop1.GetValue(ty.Name, null));
            Console.ReadLine();
        }

    }

    public static class Foo
    {
        private static string a = "hello world";
        public static string Temp
        {
            get
            {
                return a;
            }
        }
    }

Msdn

答案 1 :(得分:0)

您可以使用以下函数动态获取对象的属性值:
只是将对象传递给扫描&财产名称

public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}
相关问题