|
|
由于,我定义了一个实体,属性比较多,如果一个一个的判断是否赋值了,太麻烦了,
怎么办???自己写个方法呗。
但是,问题又来了,我想设置有些属性可以为空怎么办????可以为空的属性,请放到string[]里面传过去,就不会判断了
code如下:
- A a = new A
- {
- a1 = true,
- a2 = "1111"
- };
- bool reslut1 = IsClassNull<A>(a, null);
- bool reslut2 = IsClassNull<A>(a, new string[] { "a3" });
复制代码
- public class A
- {
- public bool a1 { get; set; }
- public string a2 { get; set; }
- public string a3 { get; set; }
- }
复制代码
方法如下:
- /// <summary>
- /// 反射判断对象属性是否赋值
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="t"></param>
- /// <param name="canNull"></param>
- /// <returns></returns>
- public bool IsClassNull<T>(T t,string[] canNull) where T : class
- {
- Type type = typeof(T);
- PropertyInfo[] ps = type.GetProperties();
- foreach (PropertyInfo info in ps)
- {
- if (canNull != null && canNull.Contains(info.Name))
- {
- continue;
- }
- else
- {
- object o = info.GetValue(t, null);
- if (o == null)
- {
- return false;
- }
- }
- }
- return true;
- }
复制代码
|
上一篇:webapi 无法将多个参数(sb和sb1)绑定到请求的内容下一篇:.net/c#模拟post登陆apple苹果网站,并获取用户信息
|