反射.我们可以使用它实现什么?

编程入门 行业动态 更新时间:2024-10-26 09:35:49
本文介绍了反射.我们可以使用它实现什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在阅读和学习 C# 中的反射.知道它如何在我的日常工作中帮助我就好了,所以我希望比我更有经验的人告诉我使用它可以实现哪些类型的事情的示例或想法,或者我们如何减少代码量我们写的.

I'm reading and learning about reflection in C#. It would be fine to know how can it help me in my daily work, so I want people with more experience than me tell me samples or ideas about what kinds of things can we achieve using it, or how can we reduce de amount of code that we write.

谢谢.

推荐答案

我最近使用它为枚举中的字段添加自定义属性:

I recently used it to add custom attributes to fields in my enum:

public enum ShapeName { // Lines [ShapeDescription(ShapeType.Line, "Horizontal Scroll Distance", "The horizontal distance to scroll the browser in order to center the game.")] HorizontalScrollBar, [ShapeDescription(ShapeType.Line, "Vertical Scroll Distance", "The vertical distance to scroll the browser in order to center the game.")] VerticalScrollBar, }

使用反射获取字段:

public static ShapeDescriptionAttribute GetShapeDescription(this ShapeName shapeName) { Type type = shapeName.GetType(); FieldInfo fieldInfo = type.GetField(shapeName.ToString()); ShapeDescriptionAttribute[] attribs = fieldInfo.GetCustomAttributes(typeof(ShapeDescriptionAttribute), false) as ShapeDescriptionAttribute[]; return (attribs != null && attribs.Length > 0) ? attribs[0] : new ShapeDescriptionAttribute(ShapeType.NotSet, shapeName.ToString()); }

属性类:

[AttributeUsage(AttributeTargets.Field)] public class ShapeDescriptionAttribute: Attribute { #region Constructor public ShapeDescriptionAttribute(ShapeType shapeType, string name) : this(shapeType, name, name) { } public ShapeDescriptionAttribute(ShapeType shapeType, string name, string description) { Description = description; Name = name; Type = shapeType; } #endregion #region Public Properties public string Description { get; protected set; } public string Name { get; protected set; } public ShapeType Type { get; protected set; } #endregion }

更多推荐

反射.我们可以使用它实现什么?

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

发布评论

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

>www.elefans.com

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