Reputation: 13083
Let's say I have some content classes like Page, TabGroup, Tab, etc. Certain of those will be implementing my IWidgetContainer interface - it means they will geet an additional field named ContainedItems from the interface and some methods for manipulating this field.
Now I need to reflect the fact that some class implements this interface by rendering out some special custom controls in my ASP.NET MVC Views (like jQuery Add/Remove/Move/Reorder buttons).
For instance, TabGroup will implement IWidgetContainer because it will contain tabs but a tab will not implement it because it won't have the ability to contain anything.
So I have to somehow check in my view, when I render my content objects (The problem is, I use my base class as strong type in my view not concrete classes), whether it implements IWidgetContainer.
How is that possible or have I completely missed something?
To rephrase the question, how do you reflect some special properties of a class (like interface implementation) in the UI in general (not necessarily ASP.NET MVC)?
Here's my code so far:
[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;
}
}
Interface:
interface IWidgetContainer
{
[DataMember]
ContentList ContainedItems { get; set; }
void AddContent(ContentListItem toAdd);
void RemoveContent(ContentListItem toRemove);
}
Upvotes: 1
Views: 561
Reputation: 42229
You can check at runtime if a class/interface derives from another class/interface like so
public static class ObjectTools
{
public static bool Implements(Type sourceType, Type implementedType)
{
if(implementedType.IsAssignableFrom(sourceType))
{
return true;
}
return false;
}
}
All you need to do is enter the type you are checking into the sourceType parameter (X), and the type you are testing against into the implementedType parameter (Y), like so
Console.WriteLine(ObjectTools.Implements(typeof(X), typeof(Y)));
Upvotes: 0
Reputation: 273209
I think you are looking for
void Foo(ContentClass cc)
{
if (cc is IWidgetContainer)
{
IWidgetContainer iw = (IWidgetContainer)cc;
// use iw
}
}
Upvotes: 3
Reputation: 39615
I may have misunderstood your question, but is there a problem with using the is
keyword?
<% if (obj is IWidgetContainer) { %>
<!-- Do something to render container-specific elements -->
<% } %>
Upvotes: 2