我的问题源于 MVC 的 SelectList (和前几代)。基本上,该类采用 IEnumerable 并使用您定义为字符串的成员。
- 它如何与对象交互(转换、反射?)
- (可能是多余的)它如何将成员查找为字符串。
这是 C# 的一个方面,我一直很感兴趣,但永远找不到 :(
编辑:
我最终使用了 System.Web.UI 中的 DataBinder.Eval()
它仍然有反射的开销,但通过允许您传递对象和包含所需成员的层次结构 的字符串,使事情变得更容易。现在这并没有多大意义,但这个项目旨在接收 Linq 数据,所以以后不用担心它让我的生活更轻松。
感谢大家的帮助。
最佳答案
虽然我不确定它的实现,但我希望它使用反射。
基本上你调用Type.GetProperty
或 Type.GetMethod
获取相关成员,然后向它询问特定实例的该属性的值(或调用方法等)。或者有 Type.GetMembers
, Type.GetMember
等
据我所知,如果您希望能够使用“Person.Mother.Name”或类似的“路径”,您必须自己进行解析。 (可能有一些框架可以为你做这件事,但它们不在反射 API 中。)
这是一个简短但完整的示例:
using System;
using System.Reflection;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Test
{
static void Main()
{
Person jon = new Person { Name = "Jon", Age = 33 };
ShowProperty(jon, "Name");
ShowProperty(jon, "Age");
}
static void ShowProperty(object target, string propertyName)
{
// We don't need no stinkin' error handling or validity
// checking (but you do if you want production code)
PropertyInfo property = target.GetType().GetProperty(propertyName);
object value = property.GetValue(target, null);
Console.WriteLine(value);
}
}
关于c# - 在 C# 中通过字符串获取成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1745061/