I'd like to return a class type from a method call, then create an instance of that returned class. I'm guessing it's got something to do with reflection / the 'Type' object? Any help would be greatly appreciated!
In delphi you'd be able to do it as follows:
unit Unit2;
interface
type
TEnum = (enString, enInteger);
TClassType = class of TClass;
TClass = class // base class type
class function ReturnClassType(Enum : TEnum) : TClassType;
end;
TClass1 = class(TClass)
public
v : string;
end;
TClass2 = class(TClass)
public
v : integer;
end;
TTesterClass = class
public
procedure Test;
end;
implementation
uses
Dialogs;
{ TClass }
class function TClass.ReturnClassType(Enum: TEnum): TClassType;
begin
case Enum of
enString : result:=TClass1;
enInteger : result:=TClass2;
end;
end;
{ TTesterClass }
procedure TTesterClass.Test;
var
ClassType : TClassType;
ValuedClass : TClass;
begin
ClassType := TClass.ReturnClassType(enInteger);
ValuedClass := ClassType.Create;
ShowMessage(ValuedClass.ClassName); // <- returns "TClass2"
end;
end.
Charles WiltshirePosted Jan 2, 2008, 7:12 PM
Cheers again
Charlie
AlanPosted Jan 1, 2008, 12:48 PM
I was just playing around some more with this and one thing I forgot to do which will enable you to access members inherited from TClass, without the need for a cast to TClass1 or TClass2, is to replace this line:
object valuedClass = Activator.CreateInstance(classType);
with this one:
TClass valuedClass = (TClass)Activator.CreateInstance(classType);
AlanPosted Jan 1, 2008, 12:18 PM
Hi Charles,
The closest I could get to that in C# is:
using System;
using System.Windows.Forms;
using System.Reflection;
enum TEnum
{
enString,
enInteger
}
class TTesterClass
{
static void Main()
{
Test();
}
static void Test()
{
Type classType = TClass.ReturnClassType(TEnum.enInteger);
object valuedClass = Activator.CreateInstance(classType);
MessageBox.Show(valuedClass.ToString());
}
}
class TClass
{
public static Type ReturnClassType(TEnum tEnum)
{
switch(tEnum)
{
case TEnum.enString:
return typeof(TClass1);
case TEnum.enInteger:
return typeof(TClass2);
default:
return null;
}
}
}
class TClass1 : TClass
{
public string v;
}
class TClass2 : TClass
{
public int v;
}
I don't know about Delphi but in C# you'd eventually have to cast valuedClass to its actual type in order to be able to do anything useful such as setting its field.