Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Replacement for "class of" in C#?

1 view
Skip to first unread message

Shawn Oster

unread,
Dec 22, 2006, 5:42:34 PM12/22/06
to
I'm trying to port a factory I use in Delphi to C# and have hit a snag. In
Delphi I usually make light-weight factories like this:

TGizmo = class(TObject)
// stuff here
end;

TGizmoClass = class of TGizmo;

TGizmoFactory = class(TObject)
private
FHashedListOfGizmoClasses: TClassHashList;
public
procedure RegisterClass(const ClassKey: string; ClassType: TGizmoClass);
function CreateObject(const ClassKey: string): TGizmo;
end;

As you can see I pass in a key and a class type, then in CreateObject I
simply look up the key in the hash, call TGizmoClass.Create and *bam* there
is my new object.

My question is: How can I create a type-safe class type to pass into my
factory? All the examples I see require creating a concrete factory for
every concrete class but that seems like a waste. I'm sure I'm just
overlooking something super simple.

Thanks,
Shawn


Joanna Carter [TeamB]

unread,
Dec 22, 2006, 6:44:47 PM12/22/06
to
"Shawn Oster" <sos...@colorflex.com> a écrit dans le message de news:
458c...@newsgroups.borland.com...

Are you using .NET 2.0 ?

If so, use the Dictionary<K,V> instead of your HashList, but a factory
method can be really simple :

public static class GizmoFactory
{
public static Gizmo CreateObject<T>() where T : Gizmo, new()
{
return new T();
}
}

This is then used like this :

public class Gizmo
{
}

public class Derived : Gizmo
{
}

void Test()
{
Gizmo g = GizmoFactory.CreateObject<Derived>();
...
}

But then I guess you might as well use the straigtforward constructor call
anyway :-(

If you want to use a string key for a hash list that has a type value, then
this becomes a bit more difficult and you will have to lose type safety in
order to use Activator.CreateInstance() instead to create your instances.

I have created a C# metaclass but it is not typesafe at compile time, if you
use System.Type as the value part of a Dictionary key, then you can only
check for type at runtime.

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer


Marc Rohloff [TeamB]

unread,
Dec 22, 2006, 6:47:13 PM12/22/06
to
On Fri, 22 Dec 2006 15:42:34 -0700, Shawn Oster wrote:

> My question is: How can I create a type-safe class type to pass into my
> factory? All the examples I see require creating a concrete factory for
> every concrete class but that seems like a waste. I'm sure I'm just
> overlooking something super simple.

Generally you use the System.Type object.

System.Type t = typeof(Gizmo);
or
System.Type t = GizmoInstance.GetType();

then
Gizmo g = (Gizmo)Activator.CreateInstance(t, constructor_params);

--
Marc Rohloff [TeamB]
marc rohloff -at- myrealbox -dot- com

0 new messages