Get Value from Field - CSharp System.Reflection

CSharp examples for System.Reflection:FieldInfo

Description

Get Value from Field

Demo Code


using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/* w w  w . ja  va2s .  c o  m*/

public class Main{
        public static object GetValue(object obj, string fieldName)
        {
            var fi = obj.GetType().GetField(fieldName, AllFlag);
            return fi == null ? null : fi.GetValue(obj);
        }
        public static object GetValue(Type sourceType, string fieldName)
        {
            var fi = sourceType.GetField(fieldName, StaticFlag);
            return fi == null ? null : fi.GetValue(null);
        }
        public static T GetValue<T>(string fieldName)
        {
            return (T)GetValue(typeof(T), fieldName);
        }
}

Related Tutorials