Reputation: 190941
Is there a way to do this without using the Type
class? I would rather to use generics.
abstract class MyAbstract
{
protected abstract T GetSpecialType();
private void MyPrivateFunction()
{
someT = GetSpecialType();
}
private void DoSomething<T>()
{
}
}
class MyConcrete : MyAbstract
{
protected override T GetSpecialType()
{
return SomeReallySpecialClass();
}
}
I am sure this would work (its the way I have it now), but its ugly.
abstract class MyAbstract
{
protected abstract Type GetSpecialType();
private void MyPrivateFunction()
{
Type someT = GetSpecialType();
}
private void DoSomething(Type ofT)
{
}
}
class MyConcrete : MyAbstract
{
protected override Type GetSpecialType()
{
return typeof(SomeReallySpecialClas();
}
}
or
Should I put it as a generic parameter on the abstract class?
Upvotes: 0
Views: 321
Reputation: 55184
It's not completely clear to me what you're trying to do, but perhaps something like this?
abstract class MyAbstract<T>
{
private void DoSomething()
{
// Use typeof(T) here as needed
}
}
class MyConcrete : MyAbstract<SomeReallySpecialClass>
{
// Is there any other logic here?
}
Upvotes: 2
Reputation: 27499
I can't quite work out what you are trying to achieve. (If I'm heading in the wrong direction with this answer, you might want to clarify your question a bit and add some details of what it is you are trying to do)
If you are just trying to create new objects based on a generic type parameter, you might want to take a look at the new constraint.
class ItemFactory<T> where T : new()
{
public T GetNewItem()
{
return new T();
}
}
By including the "new" constraint it ensures that any type provided when creating the ItemFactory class must have a public parameterless constructor, which means you can create new objects inside the class.
Upvotes: 0