开发者

Initializing Inherited Class Through Derived Constructor's Arguments (C#)

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 o开发者_高级运维pens 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!


You can’t do that, no. But for Stream specifically, you can derive from Stream, store the FileStream in a private field and pass all the method calls to it:

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(...); }
}

If you move the text cursor to the word Stream after the Example :, 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 the throw 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.

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)
    { }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜