如何将动态对象设置为正确的类型

时间:2014-08-06 17:32:26

标签: c# object dynamic casting

这是我移动滚动条的功能(我有水平的和垂直的)

    private void moveTheScroll(object sbar, int scrollDiff)
    {
        if (sbar is HScrollBar)
        {
            int newScrollvalue = ((HScrollBar)sbar).Value + scrollDiff;
            if (((HScrollBar)sbar).Minimum < newScrollvalue &&
                newScrollvalue < ((HScrollBar)sbar).Maximum)
                ((HScrollBar)sbar).Value = newScrollvalue;
        }
        else if (sbar is VScrollBar)
        {
            int newScrollvalue = ((VScrollBar)sbar).Value + scrollDiff;
            if (((VScrollBar)sbar).Minimum < newScrollvalue &&
                newScrollvalue < ((VScrollBar)sbar).Maximum)
            ((VScrollBar)sbar).Value = scrollDiff;
        }
    }

有没有办法在每次我想使用它时不对该对象进行类型转换并改为使用别名? 与此类似的东西(这不起作用,因为v无法初始化)

var v;
if(sbar is HScrollBar)
    v = (HScrollBar)sbar;
else if(sbar is VScrollBar)
    v = (VScrollBar)sbar;
v.Value = newValue;

1 个答案:

答案 0 :(得分:1)

如果两种类型都继承自Scrollbar类,那么您只需要执行一次转换:

private void moveTheScroll(object sbar, int scrollDiff)
{
    var scrollBar = sbar as ScrollBar;

    if(scrollBar != null)
    {
         int newScrollvalue = scrollBar.Value + scrollDiff;
         // do other works with scrollBar...
    }
}