我有两个自定义用户控件。当我想为 customUserControl 设置一些属性时,我必须这样做:
private void OnRightMouseDown(object sender, MouseButtonEventArgs e)
{
var userControl = sender as UserControl;
if (userControl != null)
switch (userControl.Name)
{
case "UserControl01":
var uc01 = sender as UserControl01;
if (uc01 != null)
{
uc01.ViewModel.IsSelected = true;
}
break;
case "UserControl02":
var uc02 = sender as UserControl02;
if (uc02 != null)
{
uc02.ViewModel.IsSelected = true;
}
break;
}
e.Handled = true;
}
我想这样做:
private void OnRightMouseDown(object sender, MouseButtonEventArgs e)
{
var userControl = sender as UserControl;
if (userControl != null)
{
var tempUc = GetUserControlType(userControl);
tempUc.ViewModel.IsSelected = true;
}
e.Handled = true;
}
为此,我制作了GetUserControlType
方法:
private static T GetUserControlType<T>(T userControl)
{
if (userControl != null)
{
var uc = userControl as UserControl;
switch (uc.Name)
{
case "UserControl01":
var tempUc1 = userControl as UserControl01;
return tempUc1;
case "UserControl02":
var tempUc2 = userControl as UserControl02;
return tempUc2;
}
}
return default(T);
}
我得到错误 -Cannot convert expression type '' to return type 'T' in line return tempUc1;
我怎样才能避免它,因为我需要返回这两种类型中的一种?