【发布时间】:2022-01-05 05:52:56
【问题描述】:
我有一个带有字符串常量的类:
public static class Days
{
[Description("Wow!")]
public const string Mon = "Hi!";
}
我发现it is possible for enum to have an extension method to read Description attribute:
using System.ComponentModel;
public enum Days
{
[Description("Wow!")]
Mon
}
enum的扩展方法:
public static string ToName(this Enum value)
{
var attribute = value.GetAttribute<DescriptionAttribute>();
return attribute == null ? value.ToString() : attribute.Description;
}
然后这样称呼它:
Days.Mon.ToName()
是否可以为string 编写一个扩展方法以从Mon 字符串变量的Description 属性中获取Wow! 并为这样的字符串调用扩展方法?
string description = Days.Mon.ToName(); // Output: "Wow!"
【问题讨论】:
-
我不明白你说“你可以像 X 一样称呼它”然后你又问“你能像 X 一样称呼它吗?” - 你是在问你是否可以做你刚才说你可以做的事情..?
-
您不会从字符串的扩展方法中获取该信息。该 const 字符串不知道声明它的类。您可能会从
class Days上的扩展方法中获得它,尽管这可能不是很有用 -
@CaiusJard 抱歉,如果我不清楚。我在问如何编写这样的扩展方法。 “你可以调用它”用于枚举类型。但是,我想要字符串类型的这种扩展方法。
-
好的。你到底想做什么?你打算用这个做什么?
-
@CaiusJard 我有时需要阅读控制器属性中的“嗨!”。有时有必要阅读这个字符串变量的描述。我想避免使用
Hi!和Wow!值创建两个字符串变量。
标签: c# asp.net-core reflection extension-methods asp.net-core-3.1