在C#中,如何动态指定对象的成员,例如PHP中的obj ["abc"] [英] In C# How to dynamically specify a member of a object, like obj["abc"] in PHP
本文介绍了在C#中,如何动态指定对象的成员,例如PHP中的obj ["abc"]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我上课
public class Employee
{
public string name = "";
public int age = 20;
}
现在我想要一个可以动态获取Employee指定成员值的函数
now I want a function that can dynamically get the value of a specified member of Employee
public class Util<T>
{
public static string GetValue(T obj, string member)
{
// how to write
}
}
以便我可以像
Employee p1 = new Employee();
string a = Util<Employee>.GetValue(p1, "age"); // a should be "20"
该怎么做?像访问成员一样在PHP中使用obj ["???"]
How to do it? like access member use obj["???"] in PHP
推荐答案
反射.在这里看看:
哦,还有这里 在我们自己的SO中!
Oh, and also here in our very own SO!
更新
叹息...这全都与"teh codez"有关...在这里,您去了
Sigh... It's all about "teh codez"... Here you go:
p1.GetType().GetProperty("age").GetValue(p1,null);
但是请务必检查链接,这里有很多东西要学习!
But do check the links, there's stuff to learn!
这篇关于在C#中,如何动态指定对象的成员,例如PHP中的obj ["abc"]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文