Chained constructers in C# - using intermediate logic
From this thread : http://geekswithblogs.net/kaju/archive/2005/12/05/62266.aspx someon开发者_JS百科e asked (in the comments) this question:
is there any way to do something like this:
public FooBar(string fooBar)
{
string[] s = fooBar.split(new char[] { ':' });
this(s[0], s[1]);
}
public Foo(string foo, string bar)
{
...
}
Well, I've run into the a situation where I need the same thing. Is it somehow possible? Thanks in advance.
EDIT
I meant this
public Foo(string fooBar)
{
string[] s = fooBar.split(new char[] { ':' });
this(s[0], s[1]);
}
public Foo(string foo, string bar)
{
...
}
Foo is a constructor.
My problem is that I have to do a lot of logic - including some IO stuff - before calling the other constructor.
Not directly, but:
public FooBar(string fooBar)
: this(fooBar.Split(new char[] { ':' }))
{
}
private FooBar(string[] s)
: this(s[0], s[1])
{
}
public FooBar(string foo, string bar)
{
...
}
As you mention, you may need to do "some IO stuff - before calling the other constructor." Maybe you want a static creation method?
public static FooBar LoadFromFile(string fileName)
{
var foo = "Default";
var bar = "Other Default";
// load from the file, do a bunch of logic,
return new FooBar(foo, bar);
}
精彩评论