简体   繁体   English

如何创建可能返回 null 的 class?

[英]How to create a class that may return null?

I'm stuck in creating a class that may or may not return a null value.我一直在创建一个class可能会或可能不会返回null值。

note: I know that I can get around this by checking whether File.Exists before creating the instance (using the "alternative" block that is specific for this code), but just curious if I can...注意:我知道我可以通过在创建实例之前检查File.Exists来解决这个问题(使用特定于此代码的“替代”块),但我只是好奇我是否可以......

Sample code:示例代码:

using System;
using System.IO;
using System.Windows.Forms;
...

internal class FormMain : Form {
    ...
    private MyClass myClass = null;
    private readonly String fileName = "/path/to/file/file.name";
 
    public FormMain() {
        /*
        // alternative
        if (File.Exists(fileName) {
            myClass = new MyClass(fileName);
            Setup();
            DoStuff();
        }
        */
        if ((myClass = new MyClass(fileName)) != null) {
            Setup();
            DoStuff();
        }
    }
    ...
}

internal class MyClass : IDisposable {
    // list of variables (all "String" type)
    ...
    public MyClass(String fileName) {
        if (File.Exists(fileName)) {
            // load file and initialize variables
        }
        /*
        // warning here when uncommented !!!
        else {
            return null;
        }
        */
    }

    public void Dispose() {
        ...
    }
}

Use a factory method.使用工厂方法。

internal static MyClass ConstructMyClass(String fileName) {
        if (File.Exists(fileName)) {
            // load file and initialize variables and return an instance of MyClass
        }
        /*
        // warning here when uncommented !!!
        else {
            return null;
        }
        */
    }

A class cannot return null, a class is only the definition of an object.一个class不能返回 null,一个 class 只是一个 ZA8CFDE6331BD59EB2AC96F8911C4B666 的定义

If you want object creation to fail, check for certain parameters in your constructor and throw an exception.如果您希望 object 创建失败,请检查构造函数中的某些参数并throw异常。

Eg:例如:

class MyClass {
    MyClass(object param) {
        if (param is string) {
            throw new ArgumentException(nameof(param), "Parameter must not be string!");
        }
    }
}

Just make sure you document this behaviour so you don't shoot yourself in the foot.只要确保你记录了这种行为,这样你就不会在脚上开枪了。

Throwing here will prevent the memory from being allocated and the object from being created.扔到这里会阻止 memory 被分配和 object 被创建。

Edit: Peter's solution is more elegant, however if going that direction, I'd go for a Try-pattern:编辑:彼得的解决方案更优雅,但是如果朝着这个方向发展,我会选择 go 作为尝试模式:

bool TryConstructObject(out MyObject obj) {
     if (File.Exists(MyFile)) {
        obj = null;
        return false;
     }

     obj = new MyObject();
     return true;
}

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

相关问题 typeof(T)可能返回null - typeof(T) may return null 如何创建可以使用两个名称空间之一的类? - How to create a class that may use one of two namespaces? 如何在代码文档中正确指定函数在C#上可能返回null? - How to properly specify on code-documentation a function may return null on C#? Blazor 在调用可能返回 `null` 的 js function 时,我应该如何获取 `IJSObjectReference`? - Blazor How should I get an `IJSObjectReference` when invoking a js function which may return `null`? 如何创建在C#中返回数据表的类? - how to create class that return datatable in c#? 从调用函数“ GetUnderlyingType”返回的引用“ GetUnderlyingType”可能为null - Reference 'GetUnderlyingType' return from call to function 'GetUnderlyingType' may be null 使用代码约定指定返回值可以为null - Using Code Contracts to specify a return value may be null 告诉调用者一个`异步任务<t> ` 方法可能返回 null</t> - Tell the caller that a `async Task<T>` method may return null 如何创建类的(多态)集合/列表/数组,其中每个类可能具有一些不同的属性 - How to create a (Polymorphism) collection/list/array of a class where each one may have some different properties 如何指定可能包含另一个类的类 - How to specify a class that may contain another class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM