我有兩個自定義userControls。而當我想設置一些屬性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;
我怎麼能AVO確定它,因爲我需要返回這兩種類型之一?
爲什麼不擺脫所有這些東西,並使用兩個不同的'MouseDown'處理程序,一個用於UserControl01,另一個用於UserControl02? – Clemens
問題是'UserControlX'不是'T'。其實你不需要'UserControlX',但是有一個'ViewModel'和'IsSelected'屬性。你爲什麼不定義合適的接口? –
@Nico:thnx爲你的想法 – Sasha