1、浅拷贝和深拷贝
[Serializable]
class Employee : ICloneable
{
public string IdCode { get; set; }
public int Age { get; set; }
public Department Department { get; set; }
public object Clone()
{
return this.MemberwiseClone();
}
/// <summary>
/// 深拷贝
/// </summary>
/// <returns></returns>
public Employee DeepClone()
{
using (Stream stream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
return formatter.Deserialize(stream) as Employee;
}
}
/// <summary>
/// 浅拷贝
/// </summary>
/// <returns></returns>
public Employee ShallowClone()
{
return Clone() as Employee;
}
}
[Serializable]
class Department
{
public int DepartmenId { get; set; }
public string Name { get; set; }
public override string ToString()
{
return DepartmenId.ToString()+Name;
}
}
2、使用dynamic来简化反射实现
public class DynamicSample
{
public string Name { get; set; }
public int Add(int a, int b)
{
return a + b;
}
}
//使用反射
DynamicSample reflectSample = new DynamicSample();
var addMethod = typeof(DynamicSample).GetMethod("Add");
int result = (int)addMethod.Invoke(reflectSample, new object[] { 1, 2 });
//使用dynamic
dynamic dynamicSample = new DynamicSample();
result = dynamicSample.Add(1, 2);
3、多数情况下使用foreach进行循环遍历,但foreach无法替代for(foreach不支持循环时对集合进行增删操作),for循环是索引器,foreach循环是迭代器