问题
Say I have a class
public class Employee
{
public string name = "";
public int age = 20;
}
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
}
}
so that I can use it like
Employee p1 = new Employee();
string a = Util<Employee>.GetValue(p1, "age"); // a should be "20"
How to do it? like access member use obj["???"] in PHP
回答1:
Reflection. Take a look here:
Reflection: Property Value by Name
Oh, and also here in our very own SO!
Update
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!
回答2:
yes, it's called Reflection. See Get property value from string using reflection in C#
回答3:
try following code:
// get value of private field: private double _number
int value = (int)typeof(p1).InvokeMember("age",
BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic,
null, p1, null);
or
// Get the FieldInfo of MyClass.
FieldInfo[] myFields = typeof(p1).GetFields(BindingFlags.Public | BindingFlags.Instance);
var age = myFields[i].GetValue(p1);
check link for more details
回答4:
Where does the parameter "age" come from? You should think about other designs where the choice of property isn't stored in a string.
For example, if you want to display a drop-down allowing the user to choose a column to sort by, you would want to pass a Comparer<Employee>
from the view to the model, this will be much MUCH faster, and also use the correct numeric sort instead of lexicographic.
回答5:
While I see a lot of usage of reflection here, maybe in your usecase you can do
object p1 = new Employee();
var employee = p1 as Employee;
// optionally you could do a nullcheck
string a = employee.age; // a should be "20"
Reflection works, but in your case I would just not go that far. but maybe you need generics then yes, go with reflection instead.
来源:https://stackoverflow.com/questions/5716766/in-c-sharp-how-to-dynamically-specify-a-member-of-a-object-like-objabc-in-p