【发布时间】:2014-05-15 16:23:46
【问题描述】:
我在玩System.ComponentModel.TypeDescriptor时发现了一些有趣的东西:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime DateOfBirth { get; set; }
public Enum Enum { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
var person = new Person();
var typeDescriptionProvider = TypeDescriptor.AddAttributes(person, new DescriptionAttribute("Some description of this person"));
// Returns no attributes if person is a *struct* instance,
// but does return the DescriptionAttribute if person is a *class* instance
--> var descriptionAttributes = TypeDescriptor.GetAttributes(person).OfType<DescriptionAttribute>().ToList();
// Always returns the DescriptionAttribute
var descriptionAttributesUsingTdp = typeDescriptionProvider.GetTypeDescriptor(person).GetAttributes().OfType<DescriptionAttribute>().ToList();
Console.ReadLine();
}
}
当Person的定义是一个类时,带有-->的那行代码找到并返回DescriptionAttribute就好了。
当我将Person 更改为结构时,代码找不到DescriptionAttribute。
这种差异背后的原因是什么?值类型不存在的引用类型有什么魔力吗?
我知道-->下面的代码行返回属性,不管Person的实例是类还是结构。这是因为the TypeDescriptionProvider returned by the AddAttributes() method call was the one that performed the addition。
【问题讨论】:
-
为我工作。您是否看到您发布的代码(以及
public struct Person)的行为,或者您是否过度简化了问题(从而解决了它)? -
奇怪!我已经编辑了问题以包含问题的屏幕截图。为什么我会遇到这种情况?
标签: c# typedescriptor