我可以在不使用反射的情况下获取字段的 PropertyInfo 或 class 中的 属性 吗?
Can I get PropertyInfo for a field or property in a class without using reflection?
我曾尝试使用表达式四处搜索,但无法找到可以在不使用反射的情况下访问 class 的字段或属性的内容。
基本上,我会在运行时得到一个字符串,我知道该字符串将是 class 的 属性,但我需要验证它确实是 [=36] =] 里面 class.
例如如果我有 class:
class Test { string a; public string b {get;set;} }
我在运行时得到字符串值 a
和 b
,我需要验证它们是否存在于 class Test
中
到目前为止,我从研究中知道我可以做到:
string one = "a";
string two = "b";
PropertyInfo result1 = typeof(Test).GetProperty(one);
PropertyInfo result2 = typeof(Test).GetProperty(two);
但是这段代码使用了反射。我想知道是否有某种方法可以不使用反射来做到这一点?
我可以使用表达式来做到这一点吗?
使用表达式,您可以通过以下方式获得 PropertyInfo
:
Test t = new Test();
t.b = "sadf";
Expression<Func<string>> exp = () => t.b;
var memExp = exp.Body as MemberExpression;
MemberInfo member = memExp.Member;
PropertyInfo property = (PropertyInfo)member;
Console.WriteLine(property.GetValue(t));
这将输出变量的 属性 的值(示例中的 sadf
)。但是你想达到什么目的?为什么不从 Type
中收集 PropertyInfo
?因为很可能在幕后,这段代码将以与您相同的方式使用反射(就像 LINQ 仍然使用循环一样,但程序员只是看不到它)。
我曾尝试使用表达式四处搜索,但无法找到可以在不使用反射的情况下访问 class 的字段或属性的内容。
基本上,我会在运行时得到一个字符串,我知道该字符串将是 class 的 属性,但我需要验证它确实是 [=36] =] 里面 class.
例如如果我有 class:
class Test { string a; public string b {get;set;} }
我在运行时得到字符串值 a
和 b
,我需要验证它们是否存在于 class Test
到目前为止,我从研究中知道我可以做到:
string one = "a";
string two = "b";
PropertyInfo result1 = typeof(Test).GetProperty(one);
PropertyInfo result2 = typeof(Test).GetProperty(two);
但是这段代码使用了反射。我想知道是否有某种方法可以不使用反射来做到这一点?
我可以使用表达式来做到这一点吗?
使用表达式,您可以通过以下方式获得 PropertyInfo
:
Test t = new Test();
t.b = "sadf";
Expression<Func<string>> exp = () => t.b;
var memExp = exp.Body as MemberExpression;
MemberInfo member = memExp.Member;
PropertyInfo property = (PropertyInfo)member;
Console.WriteLine(property.GetValue(t));
这将输出变量的 属性 的值(示例中的 sadf
)。但是你想达到什么目的?为什么不从 Type
中收集 PropertyInfo
?因为很可能在幕后,这段代码将以与您相同的方式使用反射(就像 LINQ 仍然使用循环一样,但程序员只是看不到它)。