gpt4 book ai didi

c# - 当只有一种资源(例如,Kinect 传感器)时,使用静态类/方法是一种好习惯吗?

转载 作者:行者123 更新时间:2023-11-30 23:13:21 25 4
gpt4 key购买 nike

我正在编写一个 C# 程序来为 Microsoft Kinect 录制和处理视频。我创建了一个 KinectManager 类来检查传感器的状态,并执行激活、停用和记录颜色流等操作。

因为只能插入一个 Kinect 传感器,每次运行程序时,我总是只需要一个 KinectManager 类的实例。在这种情况下,将类或其方法设为静态是一种好习惯吗?

最佳答案

虽然静态方法可能很方便,但请记住,静态不是面向对象的设计。例如。继承不起作用,静态类不能实现接口(interface)。

您还会获得更多耦合代码,因为与传递另一个实例相比,替换静态调用需要更多工作。

静态方法在不处理状态时更好(例如 ToUpperCase(string))——@Wazner 也提到过。

在这种情况下,您可以使用 Singleton pattern ,这将确保只有一个实例。

例如:

public class KinectManager {

// instance, another option is to make it lazy, but be aware if it's needs to be threadsafe.
private static KinectManager _instance = new KinectManager();

//private ctor to ensure it won't be created outside this class .
private KinectManager () {}

// The instance
public static KinectManager Instance {
get { return _instance ;}
}
}

但请注意 singleton pattern is overused in the real world .如果在有两个实例时出现问题,那么单例是确保这种情况不会发生的好方法。但是如果两个实例都可以,那么可能单例模式设计过度了。

关于c# - 当只有一种资源(例如,Kinect 传感器)时,使用静态类/方法是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43661683/

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