I was developing a program before, hoping to read out the attribute value through the attribute name, but because I was not familiar with reflection at that time, I did not find a suitable method and did a lot of repetitive work!
Then today I searched online again, and I found it, so I will share it with you.
In fact, the principle is not complicated. It is to use the attribute name to obtain the attribute value through reflection. I was not familiar with reflection before, so I didn't expect it~
I have to say that reflection is a very powerful technology. .
Here is the code, hoping to help those in need.
using System; using ; using ; using ; namespace PropertyNameGetPropertyValueDemo { class Program { static void Main(string[] args) { Person ps = new Person(); = "CTZ"; = 21; Demo dm = new Demo(); = "String"; = 1; (("Name")); (("Age")); (("Str")); (("I")); } } abstract class AbstractGetValue { public object GetValue(string propertyName) { return ().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 the above is more complicated, you can see the simplified version below.
using System; using ; using ; using ; namespace GetValue { class Program { static void Main(string[] args) { Person ps = new Person(); = "CTZ"; = 21; (("Name")); (("Age")); } } class Person { public string Name { get; set; } public int Age { get; set; } public object GetValue(string propertyName) { return ().GetProperty(propertyName).GetValue(this, null); } } }
There is only one substantive sentence:
().GetProperty(propertyName).GetValue(this, null);
Others can be ignored. .
The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!