简体   繁体   中英

How i can dynamically get a Property through a function in c#?

i have a function

public string getValue(string val)

and in this function i need to get the value from a database field:

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

How i can get the custom value from the function argument? I think i need to change the argument type:

public string getValue(UserProfile val)

But how i can get the Property or Pass the Property Name?

Thank you!!! :)

It is generally easier and more performant of you pass in the property as a function than as a string, ie change your signature to

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

(Naming conventions in .NET are that methods are to be in Pascal Case.) With this, you can then call name = property(user) .

Alternatively, you can use the string to retrieve the PropertyInfo object and use this to retrieve the property value. However, this is less performant as it requires reflection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM