类与类之间 相同属性及字段拷贝
主要是为了应付不同类之间成员的相互赋值。节省代码量。
namespace ConsoleApplication3 { public interface interTest { } public class Test : interTest { public string Name; public int Id; public int TestId; public int Property { get; set; } } public class TestClone { public string Name; public int Id; public int CloneId; public int Property { get; set; } } public static class Logic { public static MemberTypes AllowType = MemberTypes.Field | MemberTypes.Property; public static void CloneField<T, T1>(this T instance, T1 copyTo) where T : class ,interTest, new() { var instanceType = instance.GetType(); var copyType = copyTo.GetType(); var copyField = copyType.GetFields(); instanceType.GetFields().All(field => { var temp = copyField.FirstOrDefault(o => o.Name.Equals(field.Name, StringComparison.CurrentCulture) && o.FieldType == field.FieldType); if (temp == null) return true; temp.SetValue(copyTo, field.GetValue(instance)); return true; }); } public static void CloneProperty<T, T1>(this T instance, T1 copyTo) where T : class ,interTest, new() { var instanceType = instance.GetType(); var copyType = copyTo.GetType(); var copyProperties = copyType.GetProperties(); instanceType.GetProperties().All(property => { var temp = copyProperties.FirstOrDefault(o => o.Name.Equals(property.Name, StringComparison.CurrentCulture) && o.PropertyType == property.PropertyType); if (temp == null) return true; temp.SetValue(copyTo, property.GetValue(instance, null), null); return true; }); } } }
调用
class Program { static void Main(string[] args) { Test t = new Test(); t.Id = 1; t.Name = "shikyoh"; t.TestId = 12; t.Property = 600; TestClone tc = new TestClone(); t.CloneField(tc); t.CloneProperty(tc); Console.WriteLine("tc.Name:" + tc.Name); Console.WriteLine("tc.Id:" + tc.Id); Console.WriteLine("tc.Property:" + tc.Property); Console.WriteLine("tc.CloneId:" + tc.CloneId); } }
注意 类的名称必须相同,并且类型必须相同。