条件构造函数 [英] conditional constructor

查看:74
本文介绍了条件构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我创建了一个打开文件的类.

现在,我想围绕它建立一些安全性,并在创建类之前(在构造函数中)检查文件是否存在.当文件不存在时,该类应返回一个空对象或类似的对象.

格茨
Wannes

解决方案

好,所以我开始写代码,因为那是一件非常简单的事情,但是我决定只给你代码就可以了.通过不让您学习如何研究问题来使您不公.

有一个名为System.IO的库.它具有许多用于处理文件系统的良好类.其中之一是称为File的类.

它具有多种方法,其中一种方法对于该任务非常有用.

据推测,您已经创建了构造函数,因此,正如您所说的,您要做的就是检查文件是否存在.

我实际上不会返回null,但会引发新的异常.该库(System.IO)具有一个FileNotFoundException.

因此,如果文件不存在,请创建一个新的FileNotFoundException并将其抛出.


它要复杂得多.

该类继承自基类(在dll中,因此我没有源).我的类的构造函数调用此基类的构造函数.

例如:

public class MyClass : BaseClass
{
   public MyClass(filename) : base(filename)
   {

   }
}



当基类的构造函数中的文件名不存在时,它将引发异常.我如何捕获此异常并对其进行处理,或者将其作为MyClass的异常扔回去?

您可以创建一个静态方法,如

public YourClass GetObject()
{
    if(File.Exists(filename))
    {
        return new YourClass();
    }
}



这将是一个更好的方法.您还可以使用GetObject通过将公共接口指定为返回类型来获取更多类型.
:rose:


Hi,

I have created a class that opens a file.

Now I want to build some security around that and check if the file exists before creating the class (in the constructor). When the file doesn''t exist, the class should return a null object or something like that.

Grtz
Wannes

解决方案

Ok, so I started to just write out the code because that is an incredible simple thing to do, but I decided that just giving you the code would be doing you an injustice by not making you learn how to research problems.

There is a library called System.IO. This has many good classes for dealing with the file system. One of them is a class called File.

It has several methods in it, one which you would find very useful for this task.

Presumably, you''ve already created your constructor, so, as you said, all you need to do is check if the file exists.

I would actually not return null, but throw a new exception. That same library (System.IO) has a FileNotFoundException.

So, if the file doesn''t exist, create a new FileNotFoundException and throw it.


It is a little more complicated than that.

The class inherits from a base class (inside a dll, so I don''t have the sources). The constructor of my class calls the constructor of this base class.

for example:

public class MyClass : BaseClass
{
   public MyClass(filename) : base(filename)
   {

   }
}



When the filename in the constructor of the base class doesn''t exists it throws an exception. How can I catch this exception and handle it, or throw it back as an exception of MyClass


Why dont you use Factory class to handle these.

You can create a Static Method like

public YourClass GetObject()
{
    if(File.Exists(filename))
    {
        return new YourClass();
    }
}



This will be a better approach. you can also use GetObject to get more types by specifying common Interface as return type.
:rose:


这篇关于条件构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆