过时的属性 - 避免魔法字符串

问题描述 投票:0回答:1

我想将旧类标记为“已过时”,并在“已过时”属性注释中重定向到新类。但是,如果我将新类名写为

magic
字符串,我将无法使用 IDE 的威力。

例如,如果我重命名我的类,我就会失去“链接”。并且读者将无法在我的评论上 Ctrl + click 转到新课程。

官方文档确实似乎说这是不可能的,但我觉得很奇怪,没有人有这个需求。

而不是

// Mark OldProperty As Obsolete.
[ObsoleteAttribute("This property is obsolete. Use NewProperty instead.", false)]
public static string OldProperty
{ get { return "The old property value."; } }

public static string NewProperty
{ get { return "The new property value."; } }

我希望能够写作

[ObsoleteAttribute($"This property is obsolete. Use {nameof(NewProperty)} instead.", false)]

作为一种解决方法,我可以使用 XML 文档,但这不是最好的方法。

/// <remarks>Replaced by <see cref="LoadBrainIndMeasMessTable"/></remarks>
c# code-documentation obsolete
1个回答
1
投票

C# 10 (.NET 6) 已支持

public class C
{
    [Obsolete($"This property is obsolete. Use {nameof(NewProperty)} instead")]
    public static string OldProperty => "The old property value.";

    public static string NewProperty => "The new property value.";
}

在此之前,字符串连接应该适用于任何 C# 版本:

public class C
{
    [Obsolete("This property is obsolete. Use " + nameof(NewProperty) + " instead")]
    public static string OldProperty => "The old property value.";

    public static string NewProperty => "The new property value.";
}
© www.soinside.com 2019 - 2024. All rights reserved.