使用C#中的反射從字符串中獲取屬性值我正在嘗試使用我的代碼中的Reflection 1示例實現(xiàn)數(shù)據(jù)轉(zhuǎn)換。該GetSourceValue函數(shù)有一個比較各種類型的開關(guān),但我想刪除這些類型和屬性,并GetSourceValue只使用一個字符串作為參數(shù)獲取屬性的值。我想在字符串中傳遞一個類和屬性并解析屬性的值。這可能嗎?1個 原始博客文章的Web Archive版本
4 回答

慕森王
TA貢獻1777條經(jīng)驗 獲得超3個贊
這樣的事情怎么樣:
public static Object GetPropValue(this Object obj, String name) { foreach (String part in name.Split('.')) { if (obj == null) { return null; } Type type = obj.GetType(); PropertyInfo info = type.GetProperty(part); if (info == null) { return null; } obj = info.GetValue(obj, null); } return obj;}public static T GetPropValue<T>(this Object obj, String name) { Object retval = GetPropValue(obj, name); if (retval == null) { return default(T); } // throws InvalidCastException if types are incompatible return (T) retval;}
這將允許您使用單個字符串下降到屬性,如下所示:
DateTime now = DateTime.Now;int min = GetPropValue<int>(now, "TimeOfDay.Minutes");int hrs = now.GetPropValue<int>("TimeOfDay.Hours");
您可以將這些方法用作靜態(tài)方法或擴展。
- 4 回答
- 0 關(guān)注
- 1651 瀏覽
添加回答
舉報
0/150
提交
取消