C# 在运行时(动态)将EditorAttribute添加到对象';中国的特殊财产

C# 在运行时(动态)将EditorAttribute添加到对象';中国的特殊财产,c#,propertygrid,addattribute,C#,Propertygrid,Addattribute,如果我有一个像下面这样的类,其代码无法更改,那么如何在运行时向s1添加EditorAttribute class TestClass { public String s1 {get;set;} public String s2 {get;set;} } 我尝试了这个方法,但它也向s2添加了一个EditorAttribute编辑器,我不希望这样 TypeDescriptor.AddAttributes( typeof(String), new Edi

如果我有一个像下面这样的类,其代码无法更改,那么如何在运行时向
s1
添加EditorAttribute

class TestClass 
{ 
    public String s1 {get;set;} 
    public String s2 {get;set;} 
} 
我尝试了这个方法,但它也向
s2
添加了一个EditorAttribute编辑器,我不希望这样

TypeDescriptor.AddAttributes(
     typeof(String),
     new EditorAttribute ( 
          typeof(MyUITypeEditor),
          typeof(UITypeEditor)));

我该怎么做

您可以尝试使用为类实现自己的类型描述符,并重写该方法以返回一组自定义属性描述符,这将使您有机会根据需要添加任何自定义属性

拥有此自定义类型描述符后,就可以将该类的实例(可以将
TestClass
类的实例包装)绑定到PropertyGrid控件

如下所示:

public class TestClassTypeDescriptor : ICustomTypeDescriptor
{
   private TestClass mInst;

   public TestClassTypeDescriptor(TestClass inst)
   {
     mInst = inst;
   }

   //Implement ICustomTypeDescriptor
}


PropGridControl.SelectedObject = new TestClassTypeDescriptor(new TestClass());
您可能需要创建自己的和的派生版本,但实现起来非常简单