为对象增加默认测试属性值
This commit is contained in:
		
							parent
							
								
									6dc3ef807b
								
							
						
					
					
						commit
						50b87ed420
					
				@ -173,6 +173,41 @@ namespace Falcon.SugarApi
 | 
			
		||||
            }
 | 
			
		||||
            return r;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// 为对象设置测试值。
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        /// <typeparam name="T">对象的类型</typeparam>
 | 
			
		||||
        /// <param name="source">原始对象,可以为null</param>
 | 
			
		||||
        /// <param name="targetBuilder">可选,为目标对象复制</param>
 | 
			
		||||
        /// <returns>设置了测试值的对象</returns>
 | 
			
		||||
        public static T? ToTest<T>(this T? source,Action<T>? targetBuilder = null) where T : class, new() {
 | 
			
		||||
            var type = typeof(T);
 | 
			
		||||
            var typeName = type.FullName;
 | 
			
		||||
            if(typeName.IsNullOrEmpty()) {
 | 
			
		||||
                throw new Exception("typeof(T).FullName is null,can not createInstance!");
 | 
			
		||||
            }
 | 
			
		||||
            var obj = type.Assembly.CreateInstance(typeName) as T ?? throw new Exception("创建目标对象失败!");
 | 
			
		||||
            foreach(PropertyInfo p in type.GetProperties()) {
 | 
			
		||||
                if(!p.CanWrite || !p.CanRead) {
 | 
			
		||||
                    continue;
 | 
			
		||||
                }
 | 
			
		||||
                //如果属性为字符串
 | 
			
		||||
                if(p.PropertyType == typeof(string)) {
 | 
			
		||||
                    var val = source == null ? null : p.GetValue(source) as string;
 | 
			
		||||
                    if(val.IsNullOrEmpty()) {
 | 
			
		||||
                        p.SetValue(obj,p.Name);
 | 
			
		||||
                    }
 | 
			
		||||
                    else {
 | 
			
		||||
                        p.SetValue(obj,val);
 | 
			
		||||
                    }
 | 
			
		||||
                    continue;
 | 
			
		||||
                }
 | 
			
		||||
                //其他类型属性不做处理
 | 
			
		||||
            }
 | 
			
		||||
            targetBuilder?.Invoke(obj);
 | 
			
		||||
            return obj as T;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    /// <summary>
 | 
			
		||||
 | 
			
		||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user