限制字符串类型的方法参数来自一个给定类别的const字段



假设我们有一些方法

public class SomeClass 
{
    public Sth GetByKey(string key) 
    {
        //not important
    }
}
static class SomeKeys
{
    public static string Abc = "Abc";
    public static string Xyz = "Xyz";
}

不能通过更改。是否有一种相对简单的方法将其限制为某些项目中SomeKeys的字段传递给字段的值?因此,a.GetByKey("Qwerty")a.GetByKey("Abc")会生成一些警告或错误,并且a.GetByKey(SomeKeys.Abc)不会。

我知道这是一个糟糕的设计,依此类推,我没有寻找一种重构的方法。现在,我很好奇是否可能。我当时正在考虑写一些后的魔术,但我不知道这是否值得麻烦。它可能在编译过程中显示出错误,也可能是Resmanper中的某些魔术规则,也可能是其他内容。

编辑
另外,我不想将呼叫更改为 GetByKey,参数类型必须是字符串。

不需要原始类所需的重构或更改,只需通过Someclass(NewsomeClass)创建一个包装类,该类别(NewsomeClass)照顾强烈键入,开始在各处使用NewsomeClass。比实施一些Roslyn/ReSharper技巧要容易得多,您需要将这些技巧部署到整个团队中。

public class NewSomeClass 
{
    private SomeClass inner;
    private NewSomeClass(SomeClass inner)
    {
      this.inner = inner;
    }
    public Sth GetByKey(SomeKey key) 
    {
        return this.inner.GetByKey(key.Value);
    }
}
public sealed class SomeKey
{    
   SomeKey(string val)
   {
      this.Value = val;
   }
   public string Value {get;}
   public static readonly SomeKey Abc = new SomeKey("Abc");
   public static readonly SomeKey Xyz = new SomeKey("Xyz");
}

相关内容

最新更新