转自:点击打开链接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
class
Test
{
public
static
string
StaticPer =
"StaticPer"
;
public
readonly
string
ReadOnlyPer =
"ReadOnlyPer"
;
public
const
string
ConstPer =
"ConstPer"
;
public
string
GetPer {
get
{
return
"GetPer"
; } }
private
string
_SetPer;
public
string
SetPer {
set
{ _SetPer = value; } }
public
string
GetSetPer {
get
;
set
; }
public
void
Ok()
{
}
}
var
obj =
new
Test();
var
type = obj.GetType();
var
p = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach
(
var
item
in
p)
{
Console.WriteLine(
"Name: {0}"
, item.Name);
}
foreach
(FieldInfo field
in
type.GetFields())
{
Console.WriteLine(
"Field: {0}, Value:{1}"
, field.Name, field.GetValue(obj));
}
|
追问:
有不循环,直接根据属性名变量一下子取出来的么?
追答:
using System.Linq; // 取出 StaticPer 属性的值 var value = type.GetFields().FirstOrDefault(f => f.Name == "StaticPer").GetValue(obj); Console.WriteLine(value);
-
提问者评价
-
太给力了,你的回答完美地解决了我的问题,非常感谢!