使用 System.Attribute 类

编程入门 行业动态 更新时间:2024-10-25 10:24:28
本文介绍了使用 System.Attribute 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我陷入了这样一种情况:使用 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 类

本文发布于:2023-11-16 12:20:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1604226.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:System   Attribute

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!