在这种情况下,静态函数在性能和资源使用方面是正确的编码实践吗?
本文关键字:编码 方面 静态函数 这种情况下 性能 资源 | 更新日期: 2023-09-27 17:54:58
在stackoverflow中有许多类似的链接,所有这些链接似乎都在处理复杂的函数(所以对我来说很难理解我真正应该去做什么)。但我的想法很简单。我只是想知道如果声明一个函数为静态正确的方式去,如果我可以管理相同的功能,甚至与非静态的方法?哪种方法使用更多内存?
下面是我要实现的示例代码,它只是显示表单:
private void btn1_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
frm.ShowDialog();
}
现在我必须从我的程序中的许多其他形式中显示这个Form1
。因此,在我想要显示Form1
的地方编写上面的代码应该更好(正确的编码实践),或者应该更好地将其定义为静态类中的静态方法,像这样:
public static class globalvars
{
public static void Form1Show()
{
Form1 frm = new Form1();
frm.ShowDialog();
}
}
然后:
private void btn1_Click(object sender, EventArgs e)
{
globalvars.Form1Show();
}
我认为如果窗体对象在我们想要显示窗体的事件下实例化(第一种非静态方法),那么在堆栈中为该进程分配的内存在执行后立即销毁;而在第二种静态方法中,分配的内存在应用程序的整个生命周期中保持不变,因此非静态方法更好,对吗?
我知道两者都有效,并且没有太大的区别,但是,哪一个是正确的编码实践,内存使用明智?
从纯粹的编码角度来看,任何避免重复代码的解决方案都是好的。在您的情况下,您可能想要添加一个静态方法到Form1:
public Form1 : Form
{
public static void CreateNew()
{
using (var form = new Form1())
{
form.ShowDialog();
}
}
[...]
}
编辑:从内存的角度来看,您提供的两个示例的行为完全相同。模态对话框应该被显式地处理(例如使用关键字)。
也许我在那里失去了什么,但我没有看到它们之间的任何区别。frm
是一个局部变量,不是一个静态字段。
从内存管理的角度来看,既然在多个地方显示相同的表单,最佳方法是实现单例模式,以确保只使用一个实例
All -我知道这不是完全相关的,因为这个问题已经回答了,但是为了回答nawfal关于单例模式的问题,我将在这里发布一个简短的描述和一些代码。
@Nawfal—单例模式用于确保在应用程序中只使用对象的单个实例。有很多不同的方法可以实现这一点,请查看MSDN单例模式介绍以获得基本的介绍。
对于非平凡对象,例如类,我喜欢使用以下代码:
1:创建一个基类
public abstract class SingletonBase<T> where T : class
{
protected SingletonBase() { }
public static T Instance
{
get { return SingletonFactory.Instance; }
}
/// <summary>
/// The singleton class factory to create the singleton instance.
/// </summary>
class SingletonFactory
{
static SingletonFactory() { }
SingletonFactory() { }
internal static readonly T Instance = GetInstance();
static T GetInstance()
{
var theType = typeof(T);
T inst;
try
{
inst = (T)theType
.InvokeMember(theType.Name,
BindingFlags.CreateInstance | BindingFlags.Instance
| BindingFlags.NonPublic,
null, null, null,
CultureInfo.InvariantCulture);
}
catch (MissingMethodException ex)
{
throw new TypeLoadException(string.Format(
CultureInfo.CurrentCulture,
"The type '{0}' must have a private constructor to " +
"be used in the Singleton pattern.", theType.FullName)
, ex);
}
return inst;
}
}
2:现在从基类
继承public class myClass : SingletonBase<myClass>
{
// this is a private constructor
myClass() { }
private void somemethod()
{
}
public void SomeOtherMethod()
{
}
}
3:最后,在你需要使用myClass的任何地方,你调用它的实例,如下所示
class Program
{
static void Main(string[] args)
{
// here you call the single instance of myClass
myClass myClassInstance = myClass.Instance;
// run the public someothermethod of myClass
myClassInstance.SomeOtherMethod();
}