gpt4 book ai didi

c# - 使用私有(private)静态方法的优势

转载 作者:IT王子 更新时间:2023-10-29 03:29:54 24 4
gpt4 key购买 nike

当创建一个具有内部私有(private)方法的类时,通常是为了减少代码重复,不需要使用任何实例字段,将方法声明为静态是否有性能或内存优势?

例子:

foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample"))
{
string first = GetInnerXml(element, ".//first");
string second = GetInnerXml(element, ".//second");
string third = GetInnerXml(element, ".//third");
}

...

private static string GetInnerXml(XmlElement element, string nodeName)
{
return GetInnerXml(element, nodeName, null);
}

private static string GetInnerXml(XmlElement element, string nodeName, string defaultValue)
{
XmlNode node = element.SelectSingleNode(nodeName);
return node == null ? defaultValue : node.InnerXml;
}

将 GetInnerXml() 方法声明为静态方法有什么好处吗?没有意见请回复,我有意见。

最佳答案

来自FxCop rule page对此:

After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.

关于c# - 使用私有(private)静态方法的优势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/135020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com