通过派生构造函数的参数初始化继承类 (C#)
天啊,标题可能不是最好的,但我是一个相当新的程序员,对继承类没有太多经验。我正在尝试初始化一个类(我自己的 Stream 派生自普通 FileStream 类),并可以选择从派生的参数初始化基类。例如......
public class Example : FileStream
{
public Example(FileStream FS) : base = FS
}
显然我不能这样做,但它最好地展示了我想要做什么。我这样做的主要原因是因为流相互矛盾——我的意思是在这个类中,另一个类自动打开文件(并进行一些读取和诸如此类的操作),并且我抛出了一个异常文件无法访问。也许我做错了,但感谢大家的时间!
Hell, the title probably wasn't the best, but I'm a fairly new programmer and haven't had much experience with inherited classes. I'm trying to initialize a class (my own Stream derived from the normal FileStream class) and have the option of initializing the base from the derived's arguments. For example...
public class Example : FileStream
{
public Example(FileStream FS) : base = FS
}
Obviously I can't just do that, but it best shows what I'd like to do. The main reason why I'm doing this is because of contradicting streams -- and what I mean by that is that within this class, another class automatically opens the file (and does some reading and whatnot) and I get thrown an exception that the file is inaccessible. Maybe I'm doing this wrong, but thanks for everyone's time!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能那样做,不。但对于
Stream
具体来说,您可以从Stream
派生,将FileStream
存储在私有字段中并将所有方法调用传递给它:如果您将文本光标移动到
Example :
后面的Stream
一词,按Alt+Shift+F10并选择“实现抽象类Stream”,它将生成所有方法声明你,但你仍然需要将所有抛出新的NotImplementedException()
更改为对_underlying
的正确调用。You can’t do that, no. But for
Stream
specifically, you can derive fromStream
, store theFileStream
in a private field and pass all the method calls to it:If you move the text cursor to the word
Stream
after theExample :
, press Alt+Shift+F10 and choose “Implement abstract class Stream”, it will generate all the method declarations for you, but you will still have to change all thethrow new NotImplementedException()
into the proper calls to_underlying
.正如您所预料的,您在语法中犯了错误,您可以
帮助这个例子。
As you might expected, you're making a mistake in the syntax, you can
help with this example.