In delphi I can declare a type of class like so
type
TFooClass = class of TFoo;
TFoo=class
end;
Which is the C# equivalent for this declaration?
The closest you can get in C# is the Type
type, which contains the metadata about a type.
public class A { }
public static int Main(string[] args)
{
Type b = typeof(A);
}
It's not exactly the same. In Delphi, "type of othertype" is itself a type that you can assign to a variable. In C# "type of othertype" is a System.Type
instance that can be assigned to any variables of type System.Type
.
As an example, in Delphi, you can do this:
type
TAClass = class of TA;
TA = class
public
class procedure DoSomething;
end;
var x : TAClass;
begin
x := TA;
x.DoSomething();
end;
You cannot do anything like this in C#; you cannot call static methods of type A from instances of Type
that happen to hold typeof(A)
, nor can you define a variable that can only hold typeof(A)
or derived types.
(Some specific patterns that Delphi metaclass types are used for, can be accomplished using generics:
public class A { }
public class ListOfA<T> where T: A { }
In this case, T is the "type of A" or whatever derived class of A was used to construct the class.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With