C# 从泛型类型检索数据

C# 从泛型类型检索数据,c#,generics,C#,Generics,我有以下界面,可通过自定义控件和表单实现: public interface IThemeable<T> where T : ITheme { T Theme { get; set; } void ChangeTheme(); // Calls ThemeChangedEvent } 我希望iThemeTable组件能够继承父主题的ThemeColor,如果父主题也是iThemeTable,因此我制作了一个接口来提供此功能: public interface IT

我有以下界面,可通过自定义控件和表单实现:

public interface IThemeable<T> where T : ITheme
{
    T Theme { get; set; }

    void ChangeTheme(); // Calls ThemeChangedEvent
}
我希望
iThemeTable
组件能够继承父主题的
ThemeColor
,如果父主题也是
iThemeTable
,因此我制作了一个接口来提供此功能:

public interface IThemeableComponent
{
    bool InheritTheme { get; set; }
    ITheme ParentTheme { get; set; }

    void InitializeTheme();
}
initializeme
中,我将设置
ParentTheme
,因此我理想情况下希望检查组件的父级是否继承自
IThemeable
,如果是,则将
ParentTheme
设置为父级主题。但是,由于IThemeable需要泛型类型,我无法执行此操作:

// Expander.cs - class Expander : ContainerControl, IThemeable<ExpanderTheme>, IThemeableComponent

private bool _inheritTheme;
public bool InheritTheme
{
    get
    {
        return _inheritTheme;
    }
    set
    {
        // Check whether the parent is of type IThemeable
        _inheritTheme = Parent.GetType().GetGenericTypeDefinition() == typeof (IThemeable<>) && value;
    }
}

public ITheme ParentTheme { get; set; }

public void InitializeTheme()
{
    Theme = Themes.ExpanderDefault.Clone() as ExpanderTheme;

    if (Parent.GetType().GetGenericTypeDefinition() == typeof (IThemeable<>))
    {
        ParentTheme = (Parent as IThemeable<>).Theme; // Type argument is missing
    }
}

因为
ParentTheme
只是一个
ITheme
,下面应该可以做到这一点:

ParentTheme = (ITheme)Parent.GetType().GetProperty("Theme").GetValue(Parent);

你真的需要
IThemable
是通用的吗?或者如果
Theme
的类型是
ITheme
而不是
T
,这样可以吗?因此
IThemable
将变成非泛型
IThemable
,从而消除问题。@Mark我编辑了我的问题,以提供有关我为什么使用泛型的详细信息。创建一个非泛型
IThemable
接口,让泛型
IThemable
从中继承如何?通过这种方式,您可以检查非泛型接口。@qqww2如何从非泛型
IThemeable
中检索主题?我想得太多了。因为
ParentTheme
只是
ITheme
,所以将
ParentTheme=(ITheme)Parent.GetType().GetProperty(“Theme”).GetValue(Parent)玩这个把戏?
// ThemedForm.cs - class ThemedForm : Form, IThemeable<FormTheme>

private FormTheme _theme;

[DisplayName("Theme")]
[Category("Appearance")]
[Description("The Theme for this form.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Editor(typeof(ThemeTypeEditor), typeof(UITypeEditor))]
[TypeConverter(typeof(ExpandableObjectConverter))]
public FormTheme Theme
{
    get { return _theme; }
    set
    {
        _theme = value;
        ChangeTheme();
    }
}
ParentTheme = (ITheme)Parent.GetType().GetProperty("Theme").GetValue(Parent);