System.ComponentModel 命名空间是 .NET Framework/.NET Core 中的重要组成部分,广泛用于:

  • 属性描述与元数据特性(Attribute)
  • 数据绑定(INotifyPropertyChanged)
  • 组件设计器支持
  • 类型转换与描述器

🧩 一、System.ComponentModel 命名空间常用特性(Attributes)

这些特性(Attribute)主要用于修饰类、属性、方法等,在设计器、绑定系统、序列化中具有特殊意义。

特性名说明
BrowsableAttribute控制属性是否出现在设计器中(如属性面板)
CategoryAttribute给属性分组显示
DescriptionAttribute添加工具提示说明
DisplayNameAttribute设置属性的 UI 显示名称
DefaultValueAttribute指定属性默认值
ReadOnlyAttribute指示属性是否为只读
BindableAttribute是否支持数据绑定
DesignOnlyAttribute属性是否只在设计时可用
EditorBrowsableAttribute控制 IntelliSense 可见性
TypeConverterAttribute指定类型转换器
NotifyParentPropertyAttribute通知父属性改变
DesignerCategoryAttribute指定设计器类别(如 “Form”, “Component”)
InheritanceAttribute指示类的继承行为
LicenseProviderAttribute指定许可证提供程序

✍ 示例代码:使用特性定义属性

using System.ComponentModel;

public class Person
{
    [Category("基本信息")]
    [DisplayName("姓名")]
    [Description("用户的全名")]
    [DefaultValue("张三")]
    [Browsable(true)]
    public string Name { get; set; }

    [Category("基本信息")]
    [DisplayName("年龄")]
    [Description("用户的年龄")]
    [ReadOnly(false)]
    [Bindable(true)]
    public int Age { get; set; }
}

🔧 二、常用接口(用于数据绑定和组件交互)

接口名功能说明
INotifyPropertyChanged属性变更通知(用于 MVVM 数据绑定)
INotifyPropertyChanging属性修改前通知
INotifyDataErrorInfo支持数据验证错误通知
IDataErrorInfoWPF 中旧的数据验证机制
IComponent所有组件的基本接口
ISite组件与容器间连接的接口
ICustomTypeDescriptor自定义类型元数据暴露接口

🚀 三、常用类:描述、转换与设计支持

类名功能
TypeDescriptor获取类型的属性、事件、特性等(反射+元数据)
PropertyDescriptor描述单个属性
EventDescriptor描述事件
TypeConverter类型转换器基类
ExpandableObjectConverter支持对象在属性面板中展开
StringConverterBooleanConverter内置类型转换器
LicenseManager控制许可证检查
ComponentContainer组件与容器设计支持
EventHandlerList高效管理多个事件委托

🧪 示例:INotifyPropertyChanged 应用(数据绑定)

public class User : INotifyPropertyChanged
{
    private string name;

    public string Name
    {
        get => name;
        set 
        {
            if (value != name)
            {
                name = value;
                OnPropertyChanged(nameof(Name));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
    }
}

🔍 四、TypeDescriptor 动态读取属性信息

var props = TypeDescriptor.GetProperties(typeof(Person));
foreach (PropertyDescriptor prop in props)
{
    Console.WriteLine($"属性名: {prop.Name}, 描述: {prop.Description}, 默认值: {prop.GetValue(new Person())}");
}

✅ 五、实际应用场景

场景使用特性
WinForms/WPF 属性编辑器[Category][Description] 等
Blazor 或绑定系统INotifyPropertyChanged
控件/组件开发ComponentDesignerCategoryAttribute
类型转换器TypeConverterExpandableObjectConverter
设计时支持BrowsableReadOnlyEditorBrowsable

🧠 小结

类型示例
属性特性[Category][Description][ReadOnly]
绑定接口INotifyPropertyChangedINotifyDataErrorInfo
设计支持ComponentISiteDesignerCategory
元数据工具TypeDescriptorTypeConverterPropertyDescriptor