试着写了个 , 望指正 /// <summary> /// 合并第二个类的值到第一个类 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> /// <param name="model2"></param> public static void EntityExtend<T>(T model, T model2) where T : Model.BaseEntity, new() { Type type = typeof(T); T t = Activator.CreateInstance<T>(); PropertyInfo[] pi = type.GetProperties(); foreach (PropertyInfo p in pi) { object obj = p.GetValue(model2, null); if (obj!=null ) { if (p.PropertyType==typeof(int)) { if ((int)obj!=0) { p.SetValue(model, obj, null); } } else { p.SetValue(model, obj, null); } } } }
T t = Activator.CreateInstance<T>(); => T t = new T();
T t = Activator.CreateInstance<T>(); 多余了 忘记删除
class A { public string name; public int age; public bool sex; public static A operator+(A left,A right) { if (string.IsNullOrEmpty(left.name)) { left.name = right.name; } return left; }
} ... A a1 = new A(); a.age=10; a.sex = true; A a2 = new A(); a.age=10; a.sex = true; a1 = a1+a2;
实例 B.name =2
合并 A和B 后, A.name=2
类似于js的extend方法
实例1
{
a=1,
b=2,
c=3
}
实例2
{
a=null,(或者a=0)
b = 4,
c=5
}
最后的结果是
{
a=1,
b=4,
c=5
}
/// <summary>
/// 合并第二个类的值到第一个类
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="model2"></param>
public static void EntityExtend<T>(T model, T model2) where T : Model.BaseEntity, new()
{ Type type = typeof(T);
T t = Activator.CreateInstance<T>();
PropertyInfo[] pi = type.GetProperties();
foreach (PropertyInfo p in pi)
{
object obj = p.GetValue(model2, null);
if (obj!=null )
{
if (p.PropertyType==typeof(int))
{
if ((int)obj!=0)
{
p.SetValue(model, obj, null);
}
}
else
{
p.SetValue(model, obj, null);
}
}
} }
=>
T t = new T();
public string name;
public int age;
public bool sex;
public static A operator+(A left,A right)
{
if (string.IsNullOrEmpty(left.name))
{
left.name = right.name;
}
return left;
}
}
...
A a1 = new A();
a.age=10;
a.sex = true;
A a2 = new A();
a.age=10;
a.sex = true;
a1 = a1+a2;