Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
838 views
in Technique[技术] by (71.8m points)

c# - Use reflection to get the value of a property by name in a class instance

Lets say I have

class Person
{
    public Person(int age, string name)
    {
        Age = age;
        Name = name; 
    }
    public int Age{get;set}
    public string Name{get;set}
}

and I would like to create a method that accepts a string that contains either "age" or "name" and returns an object with the value of that property.

Like the following pseudo code:

    public object GetVal(string propName)
    {
        return <propName>.value;  
    }

How can I do this using reflection?

I am coding using asp.net 3.5, c# 3.5

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think this is the proper syntax...

var myPropInfo = myType.GetProperty("MyProperty");
var myValue = myPropInfo.GetValue(myInstance, null);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...