C# NotSupportedException在.NET CF中克隆面板控件

C# NotSupportedException在.NET CF中克隆面板控件,c#,compact-framework,clone,C#,Compact Framework,Clone,在CF应用程序中,我使用以下代码克隆控件: private static T Clone<T>(T controlToClone) where T : Control { try { PropertyInfo[] controlProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); T instance = Activator.CreateIn

在CF应用程序中,我使用以下代码克隆控件:

private static T Clone<T>(T controlToClone) 
  where T : Control
{
  try
  {
    PropertyInfo[] controlProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    T instance = Activator.CreateInstance<T>();

    foreach (PropertyInfo propInfo in controlProperties)
    {
      if (propInfo.CanWrite)
      {
        if (propInfo.Name != "WindowTarget")
          propInfo.SetValue(instance, propInfo.GetValue(controlToClone, null), null);
      }
    }
    return instance;
  }
  catch (Exception e) { MessageBox.Show(e.InnerException.Message); return null; }
}
专用静态T克隆(T控制克隆)
其中T:控制
{
尝试
{
PropertyInfo[]controlProperties=typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
T instance=Activator.CreateInstance();
foreach(controlProperties中的PropertyInfo propInfo)
{
if(propInfo.CanWrite)
{
if(propInfo.Name!=“WindowTarget”)
SetValue(实例,propInfo.GetValue(controlToClone,null),null);
}
}
返回实例;
}
catch(异常e){MessageBox.Show(e.InnerException.Message);返回null;}
}
当我克隆一个面板控件并且循环到达“Font”属性时,我得到一个异常

带InnerException的“System.Reflection.TargetInvocationException”: “System.NotSupportedException”。


为什么会这样?有办法避免吗?

我认为任何数据类型不是值类型(或具有值类型语义)的属性都不应该以这种方式复制。对于这些类型的属性,请尝试实现深度克隆/复制。尽管如此,还是有一些属性必须过滤掉


关于字体,事实证明Font类支持
IClonable
,因此我还建议您测试该属性,并且应该使用
Clone
方法复制其类型支持的任何属性。

您不能克隆控件。它包含一个非托管的Windows句柄(用于控件的窗口),您不能这样复制。@MatthewWatson不是真正的克隆,更像是一种复制。创建新控件,然后复制controlToClone中的属性。是否已步进该控件?找出引发异常的属性。您是否需要检查CanRead而不仅仅是CanWrite?