我陷入了这样一种情况:使用 System.Attribute 类似乎(乍一看)是个好主意.
我有一个要在我的应用程序中打印的对象,我需要在每个属性之前添加一个标签(或者它之前只是一个字符串).我可以将每个属性硬编码为:
Console.WriteLine("颜色:"+obj.color);Console.WriteLine("尺寸:"+obj.size);对每个属性依此类推.但不是它,我试图创建一个不需要硬编码这个标签"的代码,这样我就可以动态打印每个属性.
我得到了类似的东西,使用 System.Attribute 类:
公共类 MyObject{[MyCustomLabel("颜色:")]公共字符串颜色;[MyCustomLabel("尺寸:")]公共字符串大小;//等等...}所以我的问题来了:检索这个属性的值不是不可能的,但它不友好,因为我不得不为它使用一些反射.
我并不是真的害怕使用反射,但似乎我正在为不是为它创建的东西使用属性.
我想知道使用属性的最佳位置在哪里,如果这真的是使用它的情况.
解决方案属性和反射齐头并进.除了一些编译器/运行时属性之外,没有办法在不反映代码的情况下使用它们.
也就是说,您的方法是合理的,您可能想看看 System.ComponentModel 命名空间中的属性,这些属性有许多类来用有用的元数据装饰属性.
I got myself in a situation where using the System.Attribute class seemed (at first glance) to be a good idea.
I have an object to be printed in my application, and I need a label before each property (or just a string before it). I could put each property hardcoded like:
Console.WriteLine("Color:"+obj.color); Console.WriteLine("Size:"+obj.size);And so on for each property. But instead of it, I was trying to create a code where this 'label' doesn't needed to be hardcoded, so I could print every property dynamically.
I got something like that, using System.Attribute class:
public class MyObject { [MyCustomLabel("Color:")] public string Color; [MyCustomLabel("Size:")] public string Size; //etc... }So here comes my problem: retrieving this Attribute's value is not impossible, but it's not friendly since I had to use some reflection for it.
I'm not really scared of using reflection, but it seemed that I was using attributes for something that it wasn't created for.
I wonder where are the best places for using attributes, and if this is really a situation for using it.
解决方案Attributes and reflection go hand in hand. With the exception of some compiler/runtime attributes, there's no way to use them with out reflecting over the code.
That said, your approach is reasonable, and you might want to take a look at the attributes in the System.ComponentModel namespace which have a number of classes to decorate properties with useful metadata.
更多推荐
使用 System.Attribute 类
发布评论