簡體   English   中英

我如何通過c#中的函數動態獲取屬性?

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

我有一個功能

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)

但我如何獲得財產或通過財產名稱?

謝謝!!! :)

作為函數而不是作為字符串傳遞屬性通常更容易且更高效,即將簽名更改為

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

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

或者,您可以使用該字符串檢索PropertyInfo對象並使用它來檢索屬性值。 然而,由於需要反射,因此性能較差。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM