【问题标题】:Understanding TypeDescriptor/PropertyDescriptor/etc了解 TypeDescriptor/PropertyDescriptor/等
【发布时间】:2010-11-30 16:48:22
【问题描述】:

查看代码:

class DataItem
{
    public DataItem(int num, string s)
    {
        Number = num;
        Str = s;
    }
    public int Number { get; set; }
    public string Str { get; set; }
}

static void Main(string[] args)
{
    var data = new DataItem(2, "hi");

    var provider = TypeDescriptor.AddAttributes(typeof(DataItem),
                                               new SerializableAttribute());

    var another = provider.CreateInstance(null, typeof(DataItem), 
                                 new Type[] { typeof(int), typeof(string) }, 
                                 new object[] { 100, "hello" }) as DataItem;

    var newProperty = TypeDescriptor.CreateProperty(another.GetType(), "Str", 
                                      typeof(string), 
                                      new DescriptionAttribute("new property"));
    //newProperty.SetValue(another, "new one");

    Console.WriteLine(newProperty.GetValue(another));
    Console.Read();
}

我对代码有几个问题:

(1) 我在 DataItem 的类型中添加了一个SerializableAttribute,这个“更改”适用于什么?我无法通过typeof(DataItem).GetCustomAttributes(true)获取这个属性。看来更改没有应用到“必要的DataItem”,它是暂时存储在TypeDescriptionProvider中的?

(2)实例another是由提供者创建的(我们添加属性的地方),我想现在这个变量和SerializableAttributedDataItem的构造函数创建的变量是一样的吗?即使我们仍然无法通过another.GetType().GetCustomAttributes 获取属性。

(3) 我认为更改暂时存储在提供程序中的另一个原因是我试图创建一个名称为Str 并键入string 的属性,该属性实际上已经存在于DataItem 中。代码将输出hello。如果我取消注释SetValue 方法,输出将是new one。我有什么误解吗?

【问题讨论】:

    标签: c# .net reflection typedescriptor propertydescriptor


    【解决方案1】:

    属性被添加到实例(数据)而不是类型。您是否尝试过 TypeDescriptor.AddAttributes(typeof(DataItem)) ?

    【讨论】:

    • 我已经编辑了我的问题。我认为在这个问题上它们是相同的。
    • 好的,在这种情况下对于 1),TypeDescriptor.GetAttributes(typeof(DataItem)) 将返回 SerializableAttribute。 System.Type 实际上是指元数据(从程序集中加载)。对于动态自定义类型,TypeDescriptor 成为引用(和关联的提供者)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    相关资源
    最近更新 更多