简体   繁体   English

如何检查是否已创建类实例或为空C#

[英]How to check if a class instance has been created or is null C#

How do you check if classinstance has been created/initialised or is null ? 如何检查classinstance是否已创建/初始化或为null

private MyClass myclass;

if(!check class has been initialised)      //<- What would that check be?
    myclass = new MyClass();

Thanks in advance 提前致谢

Just check if it is null 只需检查它是否为空

if (myclass == null)

As mentioned in your comment, 正如你的评论所述,

if (myclass.Equals(null)) 

will not work because if myclass is null, that's translated to 将无效,因为如果myclass为null,则转换为

if (null.Equals(null))

which leads to a NullReferenceException . 这会导致NullReferenceException

By the way, objects declared in class scope are automatically initialized to null by the compiler, so your line: 顺便说一下,类范围中声明的对象会被编译器自动初始化为null,所以你的行:

private MyClass myclass;

is the same as 是相同的

private MyClass myclass = null;

Objects declared in a method are forced to be assigned some initial value (even if that initial value is null). 在方法中声明的对象被强制分配一些初始值(即使该初始值为null)。

if (myclass == null)
    myclass = new MyClass();

如果您希望将类限制为单个实例,请查看Singleton设计模式: http//msdn.microsoft.com/en-us/library/ff650316.aspx

you can use this constructions for avoid checking 你可以使用这个结构来避免检查

    public class SomeClass
    {
        private MyClass _myClass;
        public MyClass MyClass
        {
            get { return _myClass ?? (_myClass = new MyClass()); }
            set { _myClass = value; }
        }
    }

    public class SomeClass
    {
        private readonly MyClass _myClass = new MyClass();
        public MyClass MyClass
        {
            get { return _myClass; }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “尚未为数据集创建数据源实例”未找到数据绑定和数据源C# - “a data source instance has not been created for dataset” no databindings and datasources found C# 如何检查文件是否已在C#中修改 - How to check if a file has been modified in c# C#:如何检查打开的文件是否已更新 - C#: How to check if a open file has been updated 如何检查动态创建的winform实例是否已经在c#中打开 - How to check if the dynamically created instance of a winform is already open in c# C# 如何访问另一个创建的List实例 class - C# How to access a List instance created by another class C#如何检查基类是否为派生类的实例 - C# how to check if base class is instance of derived class 检查从哪个 Class 创建了 object - Check from which Class the object has been created 如何检查类“是”在C#中作为变量给出的类型的实例? - How to check if class “is” an instance of a type given as a variable in C#? 您如何测试已创建对象的新实例? - How do you test that a new instance of an object has been created? 如何检查键是否被多次点击或找出一个键被按下了多长时间 c# - How to check if key has been clicked more than once or to find out how long a key has been pressed for c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM