gpt4 book ai didi

c# - 反射。我们可以使用它实现什么?

转载 作者:可可西里 更新时间:2023-11-01 08:03:05 25 4
gpt4 key购买 nike

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

谢谢。

最佳答案

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

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
}

关于c# - 反射。我们可以使用它实现什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1897712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com