[英]C# simple reflection
I have a class that contains another poco class with simple get set properties: 我有一个包含另一个带有简单的get set属性的poco类的类:
public class PersonalInformation {
public string FirstName { get; set; }
public string FirstSomethingElse { get; set; }
}
I would like to find out if the current instance's PersonalInformation.FirstName has a value. 我想找出当前实例的PersonalInformation.FirstName是否具有值。 I can't figure out how to obtain it via reflection:
我不知道如何通过反射获取它:
foreach (PropertyInfo property in this.PersonalInformation.GetType().GetProperties())
{
if (property.Name.Contains("First"))
{
if (property.GetValue(XXX, null) != null)
do something...
}
}
The instance I have is "this", which does not work, neither does this.PersonalInformation. 我拥有的实例是“ this”,它不起作用,this.PersonalInformation也不起作用。 What am I doing wrong?
我究竟做错了什么?
Thank you for your response, 感谢您的答复,
Aldo 奥尔多
Addendum: I'm using ASP.NET MVC3. 附录:我正在使用ASP.NET MVC3。 In my razor view I can do the following very easily:
在我的剃刀视图中,我可以轻松地执行以下操作:
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>
}
there is a property.Value member that returns the current value of the field. 有一个property.Value成员,它返回字段的当前值。 This field comes from a poco class, as you see above.
如上所示,该字段来自poco类。 What would be the equivalent code in the code-behind?
后面的代码中等效的代码是什么?
this.PersonalInformation
certainly should work. this.PersonalInformation
当然应该起作用。 After all, that's the target you're talking about. 毕竟,这就是您要谈论的目标。
Sample code: 样例代码:
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();
}
}
Although if you just "want to find out if the current instance's PersonalInformation.FirstName has a value" then I don't see why you're using reflection... 尽管如果您只是“想知道当前实例的PersonalInformation.FirstName是否具有值”,那么我不明白您为什么要使用反射...
GetProperties返回一个PropertyInfo [],而不是单个PropertyInfo。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.