Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 4.0 动态访问类的属性_C# 4.0_Casting - Fatal编程技术网

C# 4.0 动态访问类的属性

C# 4.0 动态访问类的属性,c#-4.0,casting,C# 4.0,Casting,嗨,我必须访问具有相同属性的不同类,我想动态访问我的类的属性 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

嗨,我必须访问具有相同属性的不同类,我想动态访问我的类的属性

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 
/// Type typ=Type.GetType(classname)

请帮我拿这个

对于静态:

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

编辑(我举例):


您可以使用以下函数动态获取对象的属性值:
只需将对象传递给scan&property name

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

您可以使用反射来动态地从类名中获取属性值。我正在尝试同样的方法,但无法正确地获取属性值。显示代码如何使用反射。@slavoo实际上我的类是一个静态类…我想动态地检索它的属性值如何在从会话检索我的类名后获取静态类属性的值refer.Thnks.It对我有用..我们不能直接访问“a”来访问字段“a”使用:
var prop1=ty.GetField(“a”,BindingFlags.Static | BindingFlags.Public);Console.WriteLine(prop1.GetValue(ty.Name))但需要将字段“a”设置为公共
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;
            }
        }
    }
public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}