最近玩silverlight 3 需要把一个 plateprojection clone
作为sealed class 不大好clone 于是想了个别的办法
Code
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using System.Collections.Generic;
namespace MMMazeControl
{
public static class DependencyObjectExtention
{
static public T Clone<T>(this T source) where T : DependencyObject
{
DependencyObject proj = (DependencyObject)Activator.CreateInstance(source.GetType());
foreach (var dp in GetTypeProperties(source))
{
proj.SetValue(dp, source.GetValue(dp));
}
return (T)proj;
}
static private System.Collections.Generic.Dictionary<Type, List<DependencyProperty>> PropertyCache = new Dictionary<Type, List<DependencyProperty>>();
static private List<DependencyProperty> GetTypeProperties(DependencyObject obj)
{
var tp = obj.GetType();
List<DependencyProperty> rval = null;
if (!PropertyCache.TryGetValue(tp, out rval))
{
var ls = new List<System.Reflection.FieldInfo>(tp.GetFields());
rval = new List<DependencyProperty>();
for (var i = 0; i < ls.Count; i++)
{
var itm = ls[i];
if (itm.FieldType == typeof(DependencyProperty))
{
rval.Add((DependencyProperty)itm.GetValue(obj));
}
}
PropertyCache.Add(tp, rval);
}
return rval;
}
}
}
用的时候很方便