[英]C# simple reflection
我有一个包含另一个带有简单的get set属性的poco类的类:
public class PersonalInformation {
public string FirstName { get; set; }
public string FirstSomethingElse { get; set; }
}
我想找出当前实例的PersonalInformation.FirstName是否具有值。 我不知道如何通过反射获取它:
foreach (PropertyInfo property in this.PersonalInformation.GetType().GetProperties())
{
if (property.Name.Contains("First"))
{
if (property.GetValue(XXX, null) != null)
do something...
}
}
我拥有的实例是“ this”,它不起作用,this.PersonalInformation也不起作用。 我究竟做错了什么?
感谢您的答复,
奥尔多
附录:我正在使用ASP.NET MVC3。 在我的剃刀视图中,我可以轻松地执行以下操作:
foreach (var property in Model.PersonalInformation.GetType().GetProperties())
{
<div class="editor-line">
@if (property.Name != null)
{
<label>@(property.Name)</label>
@Html.Editor(property.Name)
}
</div>
}
有一个property.Value成员,它返回字段的当前值。 如上所示,该字段来自poco类。 后面的代码中等效的代码是什么?
this.PersonalInformation
当然应该起作用。 毕竟,这就是您要谈论的目标。
样例代码:
using System;
using System.Reflection;
public class PersonalInformation {
public string FirstName { get; set; }
public string FirstSomethingElse { get; set; }
}
public class Foo
{
public PersonalInformation PersonalInformation { get; set; }
public void ShowProperties()
{
foreach (var property in this.PersonalInformation
.GetType()
.GetProperties())
{
var value = property.GetValue(this.PersonalInformation, null);
Console.WriteLine("{0}: {1}", property.Name, value);
}
}
}
class Test
{
static void Main()
{
Foo foo = new Foo {
PersonalInformation = new PersonalInformation {
FirstName = "Fred",
FirstSomethingElse = "XYZ"
}
};
foo.ShowProperties();
}
}
尽管如果您只是“想知道当前实例的PersonalInformation.FirstName是否具有值”,那么我不明白您为什么要使用反射...
GetProperties返回一个PropertyInfo [],而不是单个PropertyInfo。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.