我有两种方法是彼此重载
public class Car
{
public int GetPrice(string vinNumber)
{
string make = Database.GetMake(vinNumber); // expensive operation
string model = Database.GetModel(vinNumber); // expensive operation
int year = Database.GetYear(vinNumber); // expensive operation
return this.GetPrice(make, model, year);
}
public int GetPrice(string make, string model, int year)
{
// Calculate value and return
}
}
在我的示例中,GetPrice(make,model,year)重载执行起来很便宜,但GetPrice(vinNumber)方法很昂贵。问题是昂贵的方法具有最少的参数,它首先出现在C#intellisense中。
这两种方法都有效,但我想鼓励人们称之为廉价方法。但是在选择要调用的方法之前,人们往往不会查看Intellisense中的所有重载,并且在我公司的代码库中经常调用昂贵的重载。
有没有办法告诉Visual Studio为特定方法提供“intellisense priority”,以便首先显示?
答案 0 :(得分:2)
您可以使用Obsolete标记修饰方法,该标记也会根据设置生成警告或错误。
[System.Obsolete("use GetPrice(make, model, year)")]
答案 1 :(得分:1)
这是怎么回事:
你可能会考虑做的是,而不是重载,在开始时将成员命名为相同而在结尾处不同(GetMake
vs GetMakeSlow
,但显然比这更好,所以他们显示在Intellisense中一起使用,但是你应该使用它。
否则,使它们成为真正的重载,但使用XML文档在缓慢的上面发出明确的警告。
答案 2 :(得分:0)
不要这么认为。
除非您编写intellisense插件(如Resharper)并劫持默认智能感知并为用户创建程序以分配优先级。
答案 3 :(得分:0)
我能提供的唯一解决方案是评论,但这并不意味着用户会关注它们:
/// <summary>
/// This method should be used as a last resort...
/// </summary>
/// <param name="vinNumber"></param>
/// <returns></returns>
public int GetPrice(string vinNumber)
{
...
}
/// <summary>
/// This is the preferred method...
/// </summary>
/// <param name="make"></param>
/// <param name="model"></param>
/// <param name="year"></param>
/// <returns></returns>
public int GetPrice(string make, string model, int year)
{
...
}
编辑:我试过这个并没有任何区别:
class Class1
{
public static void Method(int value1) { }
public static void Method(int value1, int value2) { }
public static void Method(int value1, int value2, int value3) { }
}
class Class2
{
public static void Method(int value1, int value2, int value3) { }
public static void Method(int value1, int value2) { }
public static void Method(int value1) { }
}