c#通过反射设置和获取值

private object GetValue<T>(T obj, string propertyName)
        {
            PropertyInfo propertyInfo;
            propertyInfo = typeof(T).GetProperty("DataTime", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
            return propertyInfo.GetValue(obj, null);
        }

private void SetValue<T, K>(T obj, string propertyName, K val)
        {
            PropertyInfo propertyInfo;
            propertyInfo = typeof(T).GetProperty(propertyName, BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
            if (propertyInfo != null)
            {
                Type type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
                propertyInfo.SetValue(obj, (val == null) ? null : Convert.ChangeType(val, type), null);
            }
        }

猜你喜欢

转载自blog.csdn.net/chenpeggy/article/details/38302251