你好(又是哲学问题),
有一种private static方法无法访问实例字段,就我的阅读而言,这些方法提供了一点性能改进。
将方法标记为静态后,编译器将向这些成员发出非虚拟调用站点。发出非虚拟调用站点将阻止在运行时对每个调用进行检查,以确保当前对象指针不为空。这可以为性能敏感的代码带来可测量的性能增益。在某些情况下,无法访问当前对象实例代表正确性问题。
福克斯警察
那么当我们可以在方法参数private中放置实例字段时,为什么还要使用普通方法呢?private static这不是效率低下吗?
只是为了形象化我的意思:
public class A
{
private readonly string _key = "ssss";
public bool IsGoodKey()
{
}
private static bool ValidateKeyStatic(string key)
{
return string.IsNullOrEmpty(key);
}
private bool ValidateKey()
{
return string.IsNullOrEmpty(_key);
}
}
Run Code Online (Sandbox Code Playgroud)
现在有两种实现方式IsGoodKey:
public bool IsGoodKey()
{
return ValidateKeyStatic(_key);
}
Run Code Online (Sandbox Code Playgroud)
和
public bool IsGoodKey()
{
return ValidateKey();
}
Run Code Online (Sandbox Code Playgroud)
为什么不总是使用private static?
我在初始化集合属性时注意到奇怪的行为。
考虑:
class X
{
public IList<int> Ints { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Ints我可以这样初始化:
var theObject = new X
{
Ints = { 12, 3, 4, 5, 6 }
};
Run Code Online (Sandbox Code Playgroud)
但我不能这样做:
var x = new X();
x.Ints = { 12, 3, 4, 5, 6 }
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?这似乎很不直观。