开发者

Is there any problem with this use of using extension methods to automatically convert textbox text for winforms UI

I did the following because: a) I am forcing myself to use newer c# language features (or ones I never used before) b) I am tired of typing out conversion code every time a text box holds a non-string value

So I came up with:

public static class MyExt
{
    public static MyTextBox Auto(this TextBox tb)
    {
        return new MyTextBox(tb);
    }
}
public class MyTextBox
{
    private TextBox _textBox;
    public 开发者_如何学PythonMyTextBox(TextBox t)
    {
        _textBox = t;
    }
    public static implicit operator string(MyTextBox o)
    {
        return o._textBox.Text;
    }
    public static implicit operator int(MyTextBox o)
    {
        return Convert.ToInt32(o._textBox.Text);
    }
}

Then if I have to pass a text box value somewhere that needs an int:

var a = new UnitCountsForm(campaign_NumberTextBox.Auto());

QUESTION: have I gone off the deep end or is does this seem like a reasonable use of extension methods combined with implicit operators?


If you decide to go ahead with this, I would suggest that you not use extension methods. As somebody else said, the primary use of extension methods is when you don't have the source. In your case, you can replace the extension method with a static factory method inside of MyTextBox. Or just eliminate the idea altogether and just write:

var mytb = new MyTextBox(tb);

I wouldn't recommend even that, though. I think the code you're writing is an unnecessary complication for at best a marginal gain.

One problem with that code is that it doesn't take possible errors into account. For example, your implicit conversion to int is going to fail of the textbox doesn't contain a valid integer. There's no simple way to modify the conversion operator to accommodate the error checking. I suppose you could write something like:

public static implicit operator int(MyTextBox o)
{
    int val;
    if (int.TryParse(o_textBox.Text, out val))
    {
        return val;
    }
    return -1;
}

But then you can't tell the difference between the user entering "-1" and the user entering "xyzzy".

And there's the further complication of validating the values. Converting to an integer is only the first step. You'll also want to make sure that number entered is within the expected bounds.

If you put those requirements together, the idea of writing some convoluted code to give you the integer representation of a textbox's value--if it's a valid integer--seems like a whole lot more work than it's worth.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜