I've not completely wrapped my head around one aspect of Generics.
Let's say I have a Generic class:
public abstract SomeClass<T> where T : SomeInterface
{
public bool DoSomethingsWithT(T theItem)
{
//doStuff!!!
}
public virtual bool IsActive
{
get { return true; }
}
}
So basicly I assume versions that inherit this class to be Active but I allow some of them to define their own.
Now later 开发者_Python百科on I'm getting an object into a method that I know will be of the type SomeClass<T>
but T could be any class implementing SomeInterface
public bool SomeMethod(object item)
{
var something = item as SomeClass;
return something.IsActive;
}
But this of course doesn't work as there is no class named SomeClass
and I also can't do SomeClass<SomeInterface>
as even if another class does inherit from this I'm unable to cast this.
How is this normally done? Should we create a class named SomeClass
that SomeClass<SomeInterface>
inherits from and in that class we define the IsActive
property.
I'm seeing this same exact problem If I was gonna create a collection of items that inherit SomeClass<SomeInterface>
.
How about deriving from a class/implementing an interface that contains the common behaviour:
interface IIsActive
{
bool IsActive{get;}
}
Use an interface to implement on the generic class:
interface ISomeClass
{
bool IsActive {get;}
}
public abstract SomeClass<T> : ISomeClass where T : SomeInterface
{
public bool DoSomethingsWithT(T theItem)
{
//doStuff!!!
}
public virtual bool IsActive
{
get { return true; }
}
}
public bool SomeMethod(object item)
{
var something = item as ISomeClass;
return something.IsActive;
}
Should we create a class named
SomeClass
thatSomeClass<SomeInterface>
inherits from and in that class we define theIsActive
property.
Yep, that's exactly what you should do (and is how this is normally done).
Or you could follow spender's advice and use an interface instead of an abstract class. This is probably better, as it accomplishes the same goal without restricting you to a rigid type hierarchy.
Use the interface not the Class implementation
public bool SomeMehtod(object item)
{
return ((SomeInterface)item).IsActive;
}
Just realized that the IsActive property and you are defining is not in the interface.
Then the best way to do this is to determine if the class is a SomeClass
and then return the IsActive
public bool SomeMethod(object item)
{
var something = item as SomeClass;
if (something != null)
{
return something.IsActive;
}
else
{
return somethingElse;
}
}
Not sure if I've got this right, but would this method signature work for SomeMethod?
public bool SomeMethod(SomeClass<SomeInterface> item)
{
return item.IsActive;
}
精彩评论