代码之家  ›  专栏  ›  技术社区  ›  Matt Casto

当泛型类型未知时,将对象强制转换为泛型类

  •  0
  • Matt Casto  · 技术社区  · 14 年前

    在Silverlight项目中,我定义了以下类。

    public class ThemeResource<T>
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public Type Type { get { return typeof(T); } }
        public string TypeName { get { return Type.FullName; } }
        public T Resource { get { return (T)Application.Current.Resources[this.Name]; } }
    }
    

    在我的代码后面有几个列表在使用这个类。

    public List<ThemeResource<SolidColorBrush>> BrushResources { get; set; }
    public List<ThemeResource<Color>> ColorResources { get; set; }
    public List<ThemeResource<FontFamily>> FontNameResources { get; set; }
    public List<ThemeResource<Thickness>> ThicknessResources { get; set; }
    public List<ThemeResource<Double>> FontSizeResources { get; set; }
    public List<ThemeResource<Style>> TextStyleResources { get; set; }
    

    <UserControl x:Name="ThemeResourcesPage" ...>
        <ListBox Style="{StaticResource BrushResourceListBoxStyle}"
                    ItemsSource="{Binding ElementName=ThemeResourcesPage, Path=BrushResources}"
                    SelectionChanged="ListBox_SelectionChanged" />
    </UserControl>
    

    这行不通:

    private void ListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        if (e.AddedItems.Count != 1)
            return;
    
        var tr = (ThemeResource<T>)e.AddedItems[0];
        var msg = string.Format("Name: {0}\nType: {1}\nDescription: {2}",
                                tr.Name, tr.TypeName, tr.Description);
        MessageBox.Show(msg);
    }
    

    如何在不知道T是什么的情况下将对象投射到资源?

    1 回复  |  直到 14 年前
        1
  •  1
  •   mqp    14 年前

    你不能。通常的解决方案如下:

    public interface IThemeResource
    {
        public string Name { get; }
        public string Description { get; }
        public string TypeName { get; }
    }
    
    public class ThemeResource<T> : IThemeResource
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public Type Type { get { return typeof(T); } }
        public string TypeName { get { return Type.FullName; } }
        public T Resource { get { return (T)Application.Current.Resources[this.Name]; } }
    }
    

    那你就可以到处转转了 IThemeResource 并获取它们的属性,而不考虑它们的具体泛型类型。