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:
Code
unit Unit2;Code
interfaceCode
typeCode
TEnum = (enString, enInteger);Code
TClassType = class of TClass;Code
TClass = class // base class typeCode
class function ReturnClassType(Enum : TEnum) : TClassType;Code
end;Code
TClass1 = class(TClass)Code
publicCode
v : string;Code
end;Code
TClass2 = class(TClass)Code
publicCode
v : integer;Code
end;Code
TTesterClass = classCode
publicCode
procedure Test;Code
end;Code
implementationCode
usesCode
Dialogs;Code
{ TClass }Code
class function TClass.ReturnClassType(Enum: TEnum): TClassType;Code
beginCode
case Enum ofCode
enString : result:=TClass1;Code
enInteger : result:=TClass2;Code
end;Code
end;Code
{ TTesterClass }Code
procedure TTesterClass.Test;Code
varCode
ClassType : TClassType;Code
ValuedClass : TClass;Code
beginCode
ClassType := TClass.ReturnClassType(enInteger);Code
ValuedClass := ClassType.Create;Code
ShowMessage(ValuedClass.ClassName); //Code
end;Code
end.
AlanRank #669 · 3.6K reputationPosted Jan 1, 2008, 7:18 AM EST
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.
AlanRank #669 · 3.6K reputationPosted Jan 1, 2008, 7:48 AM EST
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);
Charles Wiltshire3 reputationPosted Jan 2, 2008, 2:12 PM EST
Cheers again
Charlie