我如何通过c#中的函数动态获取属性?

时间:2014-02-19 13:33:54

标签: c# asp.net-mvc class argument-passing

我有一个功能

public string getValue(string val)

在这个函数中我需要从数据库字段中获取值:

using (UsersContext db = new UsersContext())
{
    UserProfile user = db.UserProfiles.Where(c => c.UserId == this.userId).FirstOrDefault()
    name = user.(val); ????????????
}

我如何从函数参数中获取自定义值?我想我需要改变参数类型:

public string getValue(UserProfile val)

但我如何获得财产或通过财产名称?

谢谢!!! :)

1 个答案:

答案 0 :(得分:2)

作为函数而不是作为字符串传递属性通常更容易且更高效,即将您的签名更改为

public string GetValue<T>(Func<UserProfile, T> property)

(.NET中的命名约定是Pascal Case中的方法。)然后,您可以调用name = property(user)

或者,您可以使用该字符串检索PropertyInfo对象并使用它来检索属性值。但是,由于需要反射,因此性能较差。