Previously in the development of a program, I hope to be able to read the attribute value through the attribute name, but because it was not familiar with reflection, so did not find the right way to do a lot of repetitive work ah!
Then today I went online to find, was I found, to share with you.
In fact, the principle is not complex, that is, through reflection using attribute names to get property values, before the reflection unfamiliar, so did not think AH ~
It has to be said that reflection is a very powerful technique.
Here's the code, hoping to help people in need.
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Namespace Propertynamegetpropertyvaluedemo
{
class program
{
static void Main (string[] args)
{ Person
PS = new Person ();
Ps. Name = "CTZ";
Ps. Age =;
Demo DM = new demo ();
Dm. STR = "String";
Dm. I = 1;
Console.WriteLine (Ps. GetValue ("Name"));
Console.WriteLine (Ps. GetValue ("Age"));
Console.WriteLine (DM. GetValue ("Str"));
Console.WriteLine (DM. GetValue ("I"));
}
Abstract class Abstractgetvalue
{Public
object GetValue (String propertyname) {return this
. GetType (). GetProperty (PropertyName). GetValue (this, null);
}
Class Person:abstractgetvalue
{public
string Name
{get; set;}
public int age
{get; set;}
}
Class Demo:abstractgetvalue
{public
string Str
{get; set;}
public int I
{get; set;}}}
If you think it's more complicated, look at the simplified version below.
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Namespace GetValue
{
class program
{
static void Main (string[] args)
{person
PS = new Person ( );
Ps. Name = "CTZ";
Ps. Age =;
Console.WriteLine (Ps. GetValue ("Name"));
Console.WriteLine (Ps. GetValue ("Age"));
}
Class person
{public
string Name
{get; set;}
public int age
{get; set;}
public Object GetValue (String propertyname)
{return this
. GetType (). GetProperty (PropertyName). GetValue (this, null);}}
There is only one sentence of substance:
this.GetType().GetProperty(propertyName).GetValue(this, null);
Others can be ignored.
The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!