通过派生构造函数的参数初始化继承的类(C#)

时间:2011-01-21 01:56:38

标签: c# class inheritance stream filestream

地狱,标题可能不是最好的,但我是一个相当新的程序员,并没有太多的继承类经验。我正在尝试初始化一个类(我自己的Stream派生自普通的FileStream类),并且可以选择从派生的参数初始化基类。例如......

public class Example : FileStream
{
public Example(FileStream FS) : base = FS
}

显然我不能这样做,但它最能表明我喜欢做什么。我这样做的主要原因是因为流是矛盾的 - 我的意思是在这个类中,另一个类自动打开文件(并做一些阅读和诸如此类的东西)并且我被抛出异常文件无法访问。也许我做错了,但感谢每个人的时间!

2 个答案:

答案 0 :(得分:4)

你做不到,不。但是对于Stream,您可以从Stream派生,将FileStream存储在私有字段中,并将所有方法调用传递给它:

public class Example : Stream
{
    private Stream _underlying;

    public Example(Stream underlying) { _underlying = underlying; }

    // Do the following for all the methods in Stream
    public override int Read(...) { return _underlying.Read(...); }
}

如果您将文本光标移动到Stream后面的单词Example :,请按Alt + Shift + F10并选择“实现抽象类流”,它将为您生成所有方法声明,但您仍需将所有throw new NotImplementedException()更改为对_underlying的正确调用。

答案 1 :(得分:-1)

正如您所料,您可能会在语法上犯错误 帮助这个例子。

public class SomeClassA
{
    public int foo1;
    public string foo2;
    public SomeClassA(int foo1, string foo2)
    {
        this.foo1 = foo1;
        this.foo2 = foo2;
    }
}
public class SomeClassB : SomeClassA
{
    public SomeClassB(int arg1, string arg2)
        : base(arg1, arg2)
    { }
}