2010-04-19 105 views
1

假设我有一些内容类,如Page,TabGroup,Tab等。 其中某些将实现我的IWidgetContainer接口 - 这意味着它们将从接口获取名为ContainedItems的附加字段以及用于操作此字段的一些方法。如何在运行时检查某个类是否实现了某个接口?

现在我需要反映的一些类实现由我的ASP.NET MVC观呈现出一些特殊的自定义控件这个接口(如jQuery添加/删除/移动/重新排序按钮)的事实。

例如,TabGroup将实现IWidgetContainer,因为它将包含选项卡,但选项卡不会实现它,因为它无法包含任何内容。

所以我必须以某种方式检查我的视图,当我呈现我的内容对象(问题是,我在我的视图中使用我的基类作为强类型而不是具体类),它是否实现了IWidgetContainer。

怎么可能或已经我就彻底错过了什么?

要改写这个问题,您如何在UI中反映一些类的特殊属性(如接口实现)(不一定是ASP.NET MVC)?

这里是我到目前为止的代码:

[DataContract] 
public class ContentClass 
{ 
    [DataMember] 
    public string Slug; 

    [DataMember] 
    public string Title; 

    [DataMember] 
    protected ContentType Type; 
} 

[DataContract] 
public class Group : ContentClass, IWidgetContainer 
{ 
    public Group() 
    { 
     Type = ContentType.TabGroup; 
    } 

    public ContentList ContainedItems 
    { 
     get; set; 
    } 

    public void AddContent(ContentListItem toAdd) 
    { 
     throw new NotImplementedException(); 
    } 

    public void RemoveContent(ContentListItem toRemove) 
    { 
     throw new NotImplementedException(); 
    } 
} 

[DataContract] 
public class GroupElement : ContentClass 
{ 
    public GroupElement() 
    { 
     Type = ContentType.Tab; 
    } 
} 

接口:

​​

回答

3

我认为你正在寻找

void Foo(ContentClass cc) 
{ 
    if (cc is IWidgetContainer) 
    { 
     IWidgetContainer iw = (IWidgetContainer)cc; 
     // use iw 
    } 

} 
2

我可能误解了你的问题,但有使用的is关键字的问题吗?

<% if (obj is IWidgetContainer) { %> 
    <!-- Do something to render container-specific elements --> 
<% } %> 
+0

号,用 “是” 没有问题的。我忘了也可以使用“is”。 ;) – mare 2010-04-19 10:30:06

0

您可以在运行时检查类/接口从另一个类/接口得出的,像这样

public static class ObjectTools 
{ 
     public static bool Implements(Type sourceType, Type implementedType) 
     { 
      if(implementedType.IsAssignableFrom(sourceType)) 
      { 
       return true; 
      } 
      return false; 
     } 
} 

所有你需要做的是输入您正在检查的类型到sourceType参数(X)中,并将您正在测试的类型输入ImpletedType参数(Y),如下所示:

Console.WriteLine(ObjectTools.Implements(typeof(X), typeof(Y))); 
相关问题