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);
            }
        }

你可能感兴趣的:(c#通过反射设置和获取值)