[英]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.