0

嗨,我必须具有相同属性的不同类,并且我想动态访问我的类的 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);

请帮助我得到这个

4

2 回答 2

1

反射

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

对于静态:

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

来自字符串的类引用

编辑(我做了例子):

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;
            }
        }
    }

登录

于 2013-07-15T07:10:35.100 回答
0

you can use following function to get a property value fron an object dynamically:
just pass object to scan & property name

public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}
于 2013-07-15T07:11:25.823 回答